Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new key to a nested dictionary in python

I need to add a key with a value that increases by one for every item in the nested dictionary. I have been trying to use the dict['key']='value' syntax but can't get it to work for a nested dictionary. I'm sure it's a very simple.

My Dictionary:

mydict={'a':{'result':[{'key1':'value1','key2':'value2'},
                        {'key1':'value3','key2':'value4'}]}}

This is the code that will add the key to the main part of the 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 to add the new key and value to the small dictionaries inside the square parentheses:

{'a':{'result':[{'key1':'value1',...,'index':'number'}]}}

If I try adding more layers to the last line of the for loop I get a 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 be integers, not unicode

I've tried various different ways of listing the nested items but no joy. Can anyone help me out here?

like image 587
adohertyd Avatar asked Nov 03 '25 20:11

adohertyd


1 Answers

The problem is that mydict is not simply a collection of nested dictionaries. It contains a list as well. Breaking up the definition helps clarify the internal structure:

dictlist = [{'key1':'value1','key2':'value2'},
            {'key1':'value3','key2':'value4'}]
resultdict = {'result':dictlist}
mydict = {'a':resultdict}

So to access the innermost values, we have to do this. Working backwards:

mydict['a'] 

returns resultdict. Then this:

mydict['a']['result']

returns dictlist. Then this:

mydict['a']['result'][0]

returns the first item in dictlist. Finally, this:

mydict['a']['result'][0]['key1']

returns 'value1'

So now you just have to amend your for loop to iterate correctly over mydict. There are probably better ways, but here's a first approach:

for inner_dict in mydict['a']['result']: # remember that this returns `dictlist`
    for key in inner_dict:
        do_something(inner_dict, key)
like image 61
senderle Avatar answered Nov 06 '25 09:11

senderle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!