Nihar
Nihar

Reputation: 373

Two dimensional array giving incorrect result in python

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 ???

Upvotes: 0

Views: 64

Answers (1)

WKPlus
WKPlus

Reputation: 7255

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)

Upvotes: 2

Related Questions