Adding a new key to a nested dictionary in python -
i need add key value increases 1 every item in nested dictionary. have been trying use dict['key']='value'
syntax can't work nested dictionary. i'm sure it's simple.
my dictionary:
mydict={'a':{'result':[{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}]}}
this code add key main part of dictionary:
for x in range(len(mydict)): number = 1+x str(number) mydict[d'index']=number print mydict #out: {d'index':d'1',d'a'{d'result':[...]}}
i want add new key , value small dictionaries inside square parentheses:
{'a':{'result':[{'key1':'value1',...,'index':'number'}]}}
if try adding more layers last line of for loop
traceback error:
traceback (most recent call last): file "c:\python27\program.py", line 34, in <module> main() file "c:\python27\program.py", line 23, in main mydict['a']['result']['index']=number typeerror: list indices must integers, not unicode
i've tried various different ways of listing nested items no joy. can me out here?
the problem mydict
not collection of nested dictionaries. contains list well. breaking definition helps clarify internal structure:
dictlist = [{'key1':'value1','key2':'value2'}, {'key1':'value3','key2':'value4'}] resultdict = {'result':dictlist} mydict = {'a':resultdict}
so access innermost values, have this. working backwards:
mydict['a']
returns resultdict
. this:
mydict['a']['result']
returns dictlist
. this:
mydict['a']['result'][0]
returns first item in dictlist
. finally, this:
mydict['a']['result'][0]['key1']
returns 'value1'
so have amend for
loop iterate correctly on mydict
. there better ways, here's first approach:
for inner_dict in mydict['a']['result']: # remember returns `dictlist` key in inner_dict: do_something(inner_dict, key)
Comments
Post a Comment