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
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.
“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.”
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
dict2.update(dict1)
This keeps all values from dict1
(it overwrites the same keys in dict2
if they exist).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With