user2175034
user2175034

Reputation: 93

Values in Dictionaries during a loop

When looping in a dictionary, how do I change the value in the loop. For example:

listt=[1,4,2]
mydict=[a:d, c:b, q:r]

I am trying to make:

for i in listt:
     for key in mydict:
           mydict[key]=i

but this does not work. What occurs is the ith value ends up being the last one. in my new dictionary, so it is always a:2, c:2, etc. Instead of a:1, b:4, q:2. I need to store the ith value I think and then use that to change the value in the dictionary. Though I am not sure what I am getting at! Any help would be appreciated!

Upvotes: 0

Views: 85

Answers (2)

unutbu
unutbu

Reputation: 880547

Keys in dicts are not ordered. So you can not control the pairing between items in listt and keys in the dict mydict.

However, the keys in an OrderedDict are ordered:

import collections

listt=[1,4,2]
mydict=collections.OrderedDict([('a','d'), ('c','b'), ('q','r')])
for item, key in zip(listt, mydict):
    mydict[key] = item

print(mydict)    

yields

OrderedDict([('a', 1), ('c', 4), ('q', 2)])

Upvotes: 1

thkang
thkang

Reputation: 11543

there are few misunderstandings with dict here:

it seems like you want to 'update' the dictonary with same keys and new values(with values supplied from new list). problem is, a dictonary does not keep stored items in order; a dictionary {a:d, c:b, q:r} does not mean you can iterate through the dictionary in [a, c, q] order.

also, you're using nested for-loops, that is why every value ends up as last vlues of listt.

you can use the collections.OrderedDict to keep things in order. and, instead of nested for-loops, use zip to combine iterators.

so, your code would be :

from collections import OrderedDict

listt = [1, 4, 2]
mydict = OrderedDict([(a, d), (c, b), (q, r)])

mydict = OrderedDict(zip(mydict.keys(), listt))

Upvotes: 0

Related Questions