MFin Awesome
MFin Awesome

Reputation: 23

Replace value of dictionary with key from another dictionary

I have the following dictionaries in Python 2.7

dict1 = {'a':0, 'b':1, 'c':2,'d':3,'e':4,'f':5}
dict2 = {'a':3, 'b':4, 'c':5}

I would like to iterate through the values in dict2 and replace them with the keys that correspond to those values in dict1 with the final dictionary being

dict3 = {'a':'d','b':'e','c':'f'}

I am trying to learn programming and have spent more than 3 hours trying different ways and searching the internet. Any help would be appreciated.

Upvotes: 2

Views: 3814

Answers (4)

Pramod Bhat
Pramod Bhat

Reputation: 578

dict3={}
for k,v in dict2.items():
    dict3[k]=sorted(dict1.keys())[v]

Upvotes: 0

ndpu
ndpu

Reputation: 22561

>>> dict1 = {'a':0, 'b':1, 'c':2,'d':3,'e':4,'f':5}
>>> dict2 = {'a':3, 'b':4, 'c':5}

>>> d1 = {v:k for k,v in dict1.iteritems()}
>>> d1
{0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f'}

>>> dict3 = {k:d1[v] for k,v in dict2.iteritems()}
>>> dict3
{'a': 'd', 'c': 'f', 'b': 'e'}

Upvotes: 4

ovgolovin
ovgolovin

Reputation: 13410

If there are different integers in dict1, you can make value->key dictionary from dict1 and then use it to find corresponding keys from dict1 for dict2:

>>> dict1_inverse = dict((v,k) for (k,v) in dict1.iteritems())
>>> dict((k, dict1_inverse[v]) for k,v in dict2.iteritems())
{'a': 'd', 'c': 'f', 'b': 'e'}

But if there are several keys in dict1 mapping for the same integer, you might get not what you want, e.g.:

>>> dict1 = {'a':0, 'b':1, 'c':4,'d':3,'e':4,'f':5}
>>> dict1_inverse = dict((v,k) for (k,v) in dict1.iteritems())
>>> dict((k, dict1_inverse[v]) for k,v in dict2.iteritems())
{'a': 'd', 'c': 'f', 'b': 'e'}

Here b could map to c or e, and the result may be different depending on where in the hash-table these keys are in the dict1.

In this case you may want something like this:

>>> dict1 = {'a':0, 'b':1, 'c':4,'d':3,'e':4,'f':5}
>>> dict1_inverse = {}
>>> for k,v in dict1.iteritems():
    dict1_inverse.setdefault(v, []).append(k)


>>> dict1_inverse
{0: ['a'], 1: ['b'], 3: ['d'], 4: ['c', 'e'], 5: ['f']}
>>> dict((k, dict1_inverse[v]) for k,v in dict2.iteritems())
{'a': ['d'], 'c': ['f'], 'b': ['c', 'e']}

Upvotes: 2

Burhan Khalid
Burhan Khalid

Reputation: 174624

>>> d1
{'a': 0, 'c': 2, 'b': 1, 'e': 4, 'd': 3, 'f': 5}
>>> d2
{'a': 3, 'c': 5, 'b': 4}
>>> d3 = {k:k2 for k2,v2 in d1.iteritems() for k,v in d2.iteritems() if v==v2}  
>>> d3
{'a': 'd', 'c': 'f', 'b': 'e'}

Upvotes: 0

Related Questions