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

时间:2018-11-17 17:31:43

标签: python dictionary

我有一个列表: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]

有人有主意吗?

3 个答案:

答案 0 :(得分:2)

其他选项,也许:

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?

答案 1 :(得分:1)

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中的键对齐。

答案 2 :(得分:0)

在Python 3.7+中使用zip,您可以这样做:

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

print(dict(zip(dic, operation)))
# {0: 5, 1: 6}