我有一个列表: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]有人有主意吗?
发布于 2018-11-17 17:36:04
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中的键对齐。
发布于 2018-11-17 17:36:05
其他选择,也许:
operation = [5,6]
dic = {0: None, 1: None}
for idx, val in enumerate(operation):
dic[idx] = val
dic #=> {0: 5, 1: 6}此处使用索引的详细信息:Accessing the index in 'for' loops?
发布于 2018-11-17 17:38:43
在Python zip中使用3.7+,您只需执行以下操作:
operation = [5,6]
dic = {0: None, 1: None}
print(dict(zip(dic, operation)))
# {0: 5, 1: 6}https://stackoverflow.com/questions/53353751
复制相似问题