Compare / merge two dictionaries

I have two dictionaries with key-value pairs as follows:

dict-1 ch:23, 100 ch:24, 95 dict-2 Ch:23, 98 ch:25, 100 

Not all keys are present in both dictionaries, and each dictionary contains about 200,000 key-value pairs. What I want to do is compare or combine the two and create an output text file, so if the key is in both dictionaries, I get both values ​​with the format of the output file, for example:

 ch:23 100 98 ch:24 95 . Ch:25 . 100 

How can i do this?

+2
source share
1 answer

Note If you use a dictionary (if not OrderedDict), the order will not be saved, so the final order of your result will not be the same as you depicted in your example

Going back to your example, If

 >>> d1={'ch:23': 100, 'ch:24': 95} >>> d2={'ch:23': 98 ,'ch:25': 100} 

You can try this

 >>> d3=collections.defaultdict(list) >>> for k,e in d1.items()+d2.items(): d3[k].append(e) 

If you want to save the order, you need to create the original dictionary as an ordered dict in the first instance

Then you can do it like

 >>> d1 OrderedDict([('ch:23', 100), ('ch:24', 95)]) >>> d2 OrderedDict([('ch:23', 98), ('ch:25', 100)]) >>> d3=collections.OrderedDict() >>> for k,e in d1.items()+d2.items(): d3.setdefault(k,[]).append(e) >>> d3 OrderedDict([('ch:23', [100, 98]), ('ch:24', [95]), ('ch:25', [100])]) >>> 
+4
source

Source: https://habr.com/ru/post/1204906/


All Articles