Waterploof
Waterploof

Reputation: 101

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 ?

Upvotes: 0

Views: 54

Answers (3)

haccks
haccks

Reputation: 106012

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.

Upvotes: 1

Austin
Austin

Reputation: 26039

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}

Upvotes: 0

iGian
iGian

Reputation: 11183

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?

Upvotes: 2

Related Questions