[英]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
的键对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.