Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 644
akira Avatar asked Jul 17 '26 11:07

akira


1 Answers

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}
like image 102
Pynchia Avatar answered Jul 19 '26 02:07

Pynchia