0

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 ?

Waterploof
  • 101
  • 6

3 Answers3

2

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?

iGian
  • 9,783
  • 3
  • 15
  • 32
1

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.

haccks
  • 97,141
  • 23
  • 153
  • 244
0

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}
Austin
  • 24,608
  • 4
  • 20
  • 43
  • 1
    Doesn't this assume `dic` keys are ordered appropriately? – jpp Nov 17 '18 at 17:39
  • @jpp, yes it does. In Python 3.7+, I believe they are inherently ordered. – Austin Nov 17 '18 at 17:40
  • 1
    Yup, the problem is we shouldn't assume OP is defining the dictionary manually in `operation` order (they may or may not be). At the least it should be noted. – jpp Nov 17 '18 at 17:41