Screenshot of a screen with code

Code Snippets: Python – How to merge two dictionaries

I want to inaugurate a column in which to make available small snippets of code that are quick and easy to use,

which have proved to be very useful in my daily workflow.

Working often with dictionaries I often need to combine them together. So let’s see an easy way to merge two dictionaries in Python 3:

# How to merge two dictionaries
# in Python 3
foo = {'first_el': 13, 'second_el': 33, 'third_el': 491}
bar = {'second_el': 3, 'third_el': 4, 'fourth_el': 667}
baz = {**foo, **bar}

baz
# >>> {'first_el': 13, 'second_el': 3, 'third_el': 4, 'fourth_el': 667}

As you can see from the output, remember that this method checks for any duplicate keys from left to right, possibly overwriting the keys in common between the two dictionaries.

If instead for some reason we had to recreate the same script on an outdated version of Python, i.e. Python 2, this would be the code to execute:

# How to merge two dictionaries
# in Python 2
foo = {'first_el': 13, 'second_el': 33, 'third_el': 491}
bar = {'second_el': 3, 'third_el': 4, 'fourth_el': 667}
baz = dict(foo, **bar)

baz
# >>> {'first_el': 13, 'second_el': 3, 'third_el': 4, 'fourth_el': 667}

Posted

in

by

Tags: