简体   繁体   English

用python中列表中的元素替换字典的值

[英]replace values of a dictionary with elements from a list in python

I have a list : operation = [5,6] and a dictionary dic = {0: None, 1: None} 我有一个列表: operation = [5,6]和字典dic = {0: None, 1: None}

And I want to replace each values of dic with the values of operation. 我想用运算的值替换dic的每个值。

I tried this but it don't seem to run. 我尝试了此操作,但它似乎没有运行。

operation = [5,6]

for i in oper and val, key in dic.items():
        dic_op[key] = operation[i]

Does someone have an idea ? 有人有主意吗?

Other option, maybe: 其他选择,也许是:

operation = [5,6]
dic = {0: None, 1: None}

for idx, val in enumerate(operation):
  dic[idx] = val

dic #=> {0: 5, 1: 6}

Details for using index here: Accessing the index in 'for' loops? 在此使用索引的详细信息: 在“ for”循环中访问索引?

zip method will do the job 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}  

The above solution assumes that dic is ordered in order that element position in operation is align to the keys in the dic . 上面的解决方案假定dic被排序,以便operation中的元素位置与dic的键对齐。

Using zip in Python 3.7+, you could just do: 在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM