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 ?

1
  • Try using zip method. Commented Nov 17, 2018 at 17:33

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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}

3 Comments

Doesn't this assume dic keys are ordered appropriately?
@jpp, yes it does. In Python 3.7+, I believe they are inherently ordered.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.