python - 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:
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? Expected 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
for i, j in zip(list1, list2):
myDict[i]['first'] = j
推荐阅读
- python - python strftime不带前导0
- google-sheets - 在表格脚本中暂停一下,睡眠不起作用
- protocol-buffers - 如何为 Protocol Buffers rpc 方法定义空参数?
- java - Pig it method that I am trying to make trouble checking punctuation at the end java
- git - new PR includes changes from older PR in Github
- google-api - YouTube API is adding 101 uses for each request instead of one
- javascript - 如何删除 Firebase 中嵌套集合的一部分?
- azure - Azure AD 帐户与 Active Directory 与租户
- python - 使用 Gekko 进行楼层划分
- python - 在 docker 环境中运行 AzureML Estimator 时缺少依赖项