![](/img/trans.png)
[英]python: iterate through list and replace elements with corresponding dictionary values
[英]replace values of a dictionary with elements from a list in python
我有一個列表: operation = [5,6]
和字典dic = {0: None, 1: None}
我想用運算的值替換dic的每個值。
我嘗試了此操作,但它似乎沒有運行。
operation = [5,6]
for i in oper and val, key in dic.items():
dic_op[key] = operation[i]
有人有主意嗎?
其他選擇,也許是:
operation = [5,6]
dic = {0: None, 1: None}
for idx, val in enumerate(operation):
dic[idx] = val
dic #=> {0: 5, 1: 6}
在此使用索引的詳細信息: 在“ for”循環中訪問索引?
zip
方法可以勝任
operation = [5, 6]
dic = {0: None, 1: None}
for key, op in zip(dic, operation):
dic[key] = op
print(dic) # {0: 5, 1: 6}
上面的解決方案假定dic
被排序,以便operation
中的元素位置與dic
的鍵對齊。
在Python 3.7+中使用zip
,您可以執行以下操作:
operation = [5,6]
dic = {0: None, 1: None}
print(dict(zip(dic, operation)))
# {0: 5, 1: 6}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.