Tim
Tim

Reputation: 39

Change key to value of same key in other dictionary

I'm looking for the following, but I won't get it. I already tried with swapping key-value pairs, but that didn't work.

The thing I'm trying to obtain, consider 2 dictionaries:

dict1 = {'a':1, 'b':20, 'c':100}
dict2 = {'a':'apple', 'b':'banana', 'c':'citrus'}

I'm trying to look for a new dictionary:

dict3 = {'apple':1, 'banana':20, 'citrus':100}

Can someone help me or give me some tips? (Both dictionaries are very large, so first I need to program it that way that it looks for the right key in dict2 - which is way larger than dict1 and not in same order as dict1).

Upvotes: 0

Views: 1551

Answers (1)

Lorenzo Vincenzi
Lorenzo Vincenzi

Reputation: 1212

Use iteritems() to iteratete key and value of a dict.

for key, value in dict2.iteritems():
    dict3[value] = dict1[key]

For Python 3.x, iteritems() has been replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems(). The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

Upvotes: 2

Related Questions