Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union of dictionaries python [duplicate]

Tags:

I have two dictionaries that I want the union of so that each value from the first dictionary is kept and all the key:value pairs from the second dictionary is added to the new dictionary, without overriding the old entries.

dict1 = {'1': 1, '2': 1, '3': 1, '4': 1} dict2 = {'1': 3, '5': 0, '6': 0, '7': 0} 

where the function dictUnion(dict1, dict2) returns

{'1': 1, '2': 1, '3': 1, '4': 1, '5': 0, '6': 0, '7': 0} 

I can, and have done it by using simple loops, this is pretty slow though when operating on large dictionaries. A faster more "pythonic" way would be appreciated

like image 646
NicolaiF Avatar asked Oct 28 '16 14:10

NicolaiF


People also ask

How do you find the union of two dictionaries in Python?

The simplest way to merge two dictionaries in python is by using the unpack operator(**). By applying the "**" operator to the dictionary, it expands its content being the collection of key-value pairs.

What is Union in dictionary in Python?

“Dict union will return a new dict consisting of the left operand merged with the right operand, each of which must be a dict (or an instance of a dict subclass). If a key appears in both operands, the last-seen value (i.e. that from the right-hand operand) wins.”

Can dictionaries in Python have duplicates?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


1 Answers

dict2.update(dict1) 

This keeps all values from dict1 (it overwrites the same keys in dict2 if they exist).

like image 123
deceze Avatar answered Oct 07 '22 18:10

deceze