繁体   English   中英

从列表中编辑嵌套字典中的值(python)

[英]Edit values in nested dictionary from the list (python)

对不起,如果有人问过,但我找不到正确的答案。 我有 2 个列表:

list1 = [1, 2, 3, 5, 8]
list2 = [100, 200, 300, 400, 500]

和一个嵌套字典:

myDict = {
    1: {'first': None, 'second': None, 'third': None} ,
    2: {'first': None, 'second': None, 'third': None} ,
    3: {'first': None, 'second': None, 'third': None} ,
    5: {'first': None, 'second': None, 'third': None} ,
    8: {'first': None, 'second': None, 'third': None} ,
    }

如何根据键在 myDict 中的每个字典中插入值? 预计 output:

myDict= {
    1: {'first': 100, 'second': None, 'third': None} ,
    2: {'first': 200, 'second': None, 'third': None} ,
    3: {'first': 300, 'second': None, 'third': None} ,
    5: {'first': 400, 'second': None, 'third': None} ,
    8: {'first': 500, 'second': None, 'third': None} ,
    }

我试过的:

for i in list1:
   for j in list2:
       myDict[i]['first'] = j
print(myDict)

我得到了什么(它将所有值替换为列表中的最后一项)

{1: {'first': 500, 'second': None, 'third': None},
2: {'first': 500, 'second': None, 'third': None},
3: {'first': 500, 'second': None, 'third': None},
5: {'first': 500, 'second': None, 'third': None},
8: {'first': 500, 'second': None, 'third': None}
}

谢谢

你需要的是zip

for i, j in zip(list1, list2):
   myDict[i]['first'] = j

您可以执行以下操作:

for k,i in zip(list1,list2):
    myDict[k]['first'] = i

和 output:

{1: {'first': 100, 'second': None, 'third': None},
 2: {'first': 200, 'second': None, 'third': None},
 3: {'first': 300, 'second': None, 'third': None},
 5: {'first': 400, 'second': None, 'third': None},
 8: {'first': 500, 'second': None, 'third': None}}

这样的事情会起作用:

i = 0 
while i < len(list1):
myDict[list1[i]]["first"] = list2[i]
i += 1

结果:

{  1: {'first': 100, 'second': None, 'third': None},
   2: {'first': 200, 'second': None, 'third': None},
   3: {'first': 300, 'second': None, 'third': None},
   5: {'first': 400, 'second': None, 'third': None},
   8: {'first': 500, 'second': None, 'third': None}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM