在python中向嵌套字典添加新密钥

ado*_*tyd 2 python dictionary

我需要为嵌套字典中的每个项添加一个值增加1的键.我一直在尝试使用dict['key']='value'语法,但无法使其适用于嵌套字典.我确定这很简单.

我的词典:

mydict={'a':{'result':[{'key1':'value1','key2':'value2'},
                        {'key1':'value3','key2':'value4'}]}}
Run Code Online (Sandbox Code Playgroud)

这是将密钥添加到字典主要部分的代码:

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':[...]}}
Run Code Online (Sandbox Code Playgroud)

我想将新的键和值添加到方括号内的小字典中:

{'a':{'result':[{'key1':'value1',...,'index':'number'}]}}
Run Code Online (Sandbox Code Playgroud)

如果我尝试在最后一行添加更多图层,for loop我会收到一个回溯错误:

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
Run Code Online (Sandbox Code Playgroud)

我已经尝试了各种不同的方式列出嵌套项目但没有快乐.有人可以帮我从这里出去吗?

sen*_*rle 8

问题是,这mydict不仅仅是嵌套字典的集合.它也包含一个列表.打破定义有助于澄清内部结构:

dictlist = [{'key1':'value1','key2':'value2'},
            {'key1':'value3','key2':'value4'}]
resultdict = {'result':dictlist}
mydict = {'a':resultdict}
Run Code Online (Sandbox Code Playgroud)

因此,要访问最内层的值,我们必须这样做.向后工作:

mydict['a'] 
Run Code Online (Sandbox Code Playgroud)

回报resultdict.然后这个:

mydict['a']['result']
Run Code Online (Sandbox Code Playgroud)

回报dictlist.然后这个:

mydict['a']['result'][0]
Run Code Online (Sandbox Code Playgroud)

返回第一项dictlist.最后,这个:

mydict['a']['result'][0]['key1']
Run Code Online (Sandbox Code Playgroud)

回报 'value1'

所以现在你只需修改你的for循环就可以正确迭代了mydict.可能有更好的方法,但这是第一种方法:

for inner_dict in mydict['a']['result']: # remember that this returns `dictlist`
    for key in inner_dict:
        do_something(inner_dict, key)
Run Code Online (Sandbox Code Playgroud)