akira
akira

Reputation: 531

merging two dictionary in python

Hi I have two dictionary as follows

{'abc':1,'xyz':8,'pqr':9,'ddd': 22}
{0:'pqr',1:'xyz',2:'abc',3:'ddd'}

My objective is to get a new dictionary in the following format

{2:1 1:8 0:9 3:22}

I am combing the value of first dictionary as value of the new dictionary and the key of dictionary 2 whose value matches with the key of the dictionary 1 as key of the the new dictionary.

I have written some code as follows:

for list1elem in listofemail[1:]:
    print(list1elem)
    for the_key, the_value in list1elem.items():
        the_key = [k for k, v in vocab_dic.items() if v == the_key]

But my code is not replacing the old key with the new one. Both of my dictionaries are large, containing 25000 key/value pair. So it is taking a lot of time. What would be the fastest way to do this?

Upvotes: 2

Views: 103

Answers (2)

Pynchia
Pynchia

Reputation: 11580

this

d1 = {'abc':1, 'xyz':8, 'pqr':9, 'ddd':22}
d2 = {0:'pqr', 1:'xyz', 2:'abc', 3:'ddd'}

d = {k:d1[v] for k,v in d2.items()}

produces

{0: 9, 1: 8, 2: 1, 3: 22}

Basically, it goes through every item (key and value) in d2 and it uses the value v as the key into d1 to get its corresponding value. It then combines the latter with the original key k to create the item that goes into the resulting dictionary.

Side note: there is no error checking. It assumes the values in d2 are present in d1 as keys.

In case you wanted a specific value if the key is missing (e.g. -1), you can do

d = {k:d1.get(v, -1) for k,v in d2.items()}

Otherwise, in case you wanted to omit inserting the item altogether, use

d = {k:d1[v] for k,v in d2.items() if v in d1}

Upvotes: 6

Rahul Gupta
Rahul Gupta

Reputation: 47846

You can do the following:

In [1]: a1 = {'abc':1,'xyz':8,'pqr':9,'ddd': 22} 

In [2]: a2 = {0:'pqr', 1:'xyz',2:'abc',3:'ddd'}

In [3]: a3 = {}

In [4]: for key, value in a2.items():
            # extra checking if the value of 2nd dictionary is a key in 1st dictionary
            if value in a1: 
                a3[key] = a1[value]    

In [5]: a3 
Out[5]: {0: 9, 1: 8, 2: 1, 3: 22} # desired result

Here we iterate over the 2nd dictionary and check if values of 2nd dictionary are present as keys in the 1st dictionary using the in operator. If they are present, then we assign the key of the 2nd dictionary as the key of a3 and value as the value obtained on performing lookup in the 1st dictionary with the value of 2nd dictionary.

Upvotes: 4

Related Questions