对不起,如果有人问过,但我找不到正确的答案。我有 2 个列表:
list1 = [1, 2, 3, 5, 8]
list2 = [100, 200, 300, 400, 500]
Run Code Online (Sandbox Code Playgroud)
和嵌套字典:
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} ,
}
Run Code Online (Sandbox Code Playgroud)
如何根据键在 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} ,
}
Run Code Online (Sandbox Code Playgroud)
我试过的:
for i in list1:
for j in list2:
myDict[i]['first'] = j
print(myDict)
Run Code Online (Sandbox Code Playgroud)
我得到了什么(它用列表中的最后一项替换所有值)
{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}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
你需要的是拉链
for i, j in zip(list1, list2):
myDict[i]['first'] = j
Run Code Online (Sandbox Code Playgroud)