[英]Edit values in nested dictionary from the list (python)
sorry if it's been asked, but I could not find the correct answer.对不起,如果有人问过,但我找不到正确的答案。 I have 2 lists:
我有 2 个列表:
list1 = [1, 2, 3, 5, 8]
list2 = [100, 200, 300, 400, 500]
and a nested dictionary:和一个嵌套字典:
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} ,
}
How do I insert values in each of dictionaries inside myDict, based on key?如何根据键在 myDict 中的每个字典中插入值? Expected output:
预计 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} ,
}
what I tried:我试过的:
for i in list1:
for j in list2:
myDict[i]['first'] = j
print(myDict)
What I get (it replaces all values with the last item in the list)我得到了什么(它将所有值替换为列表中的最后一项)
{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}
}
Thank you谢谢
What you need is zip你需要的是zip
for i, j in zip(list1, list2):
myDict[i]['first'] = j
You can do the following:您可以执行以下操作:
for k,i in zip(list1,list2):
myDict[k]['first'] = i
and the output:和 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}}
Something like this would work:这样的事情会起作用:
i = 0
while i < len(list1):
myDict[list1[i]]["first"] = list2[i]
i += 1
Result:结果:
{ 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.