简体   繁体   中英

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}

And I want to replace each values of dic with the values of operation.

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?

zip method will do the job

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 .

Using zip in Python 3.7+, you could just do:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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