0

I have this code to create 2d array by loop

result = dict()
final = dict()

with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        for key,path in path_items:
            final[key]=path
            result[entry] = final
    json.dump(result, outfile)

but in result i got all key, path for each entry ! What to do ???

3
  • That is what you are assigning, you assign final[key]=path and then result[entry] = final what do you expect to happen? You are also creating two dicts not a 2d array. Commented Jul 23, 2014 at 11:31
  • You only have one final dict, and you use it for everything. Also, you probably ought to read up on Python's data structures, because dicts aren't arrays. Commented Jul 23, 2014 at 11:32
  • ok. how can i fix this ? Commented Jul 23, 2014 at 11:32

1 Answer 1

2

From your code, I think you want a dict contains dict elements, you can do it like this:

result = dict()
with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        result[entry] = dict()
        for key,path in path_items:
            result[entry][key] = path

    json.dump(result, outfile)

If path_items is a list/tuple of list/tuple which contains two elements, you can make the code simpler like this:

result = dict()
with open(self.json_file , 'w') as outfile:
    for entry in sections_list:
        path_items = raw_config.items(entry)
        result[entry] = dict(path_items)

    json.dump(result, outfile)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.