【发布时间】:2020-07-30 02:44:52
【问题描述】:
对不起,如果有人问过,但我找不到正确的答案。我有 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 中的每个字典中插入值? 预期输出:
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}
}
谢谢
【问题讨论】:
-
你实际上做了 25 次更新而不是 5 次,每个键在 list2 中的每个值更新一次
-
@Chris 谢谢,我以为出了点问题
标签: python list dictionary