Merge Dictionaries in Python

John John (304)
5 minutes

In this guide we'll cover how to merge two (or more) dictionaries in Python. There are a few ways to do it, so we'll cover multiple methods.

For each method, we'll assume we want to merge the following dictionaries:

address = {
    'street': '123 W Pine St',
    'city': 'Centerville',
    'state': 'Indiana',
    'size_sq_ft': '2310'
}

resident = {
    'first_name': 'Leroy',
    'last_name': 'Jenkins',
}

The desired result is a single dictionary that combines the two:

result = {
    'street': '123 W Pine St',
    'city': 'Centerville',
    'state': 'Indiana',
    'size_sq_ft': '2310',
    'first_name': 'Leroy',
    'last_name': 'Jenkins',
}
Posted in these interests:
h/python67 guides

In Python 3.5+ we can merge dictionaries with a very simple expression:

result = {**address, **resident}

This creates a new dictionary altogether from the contents of address and resident.

Unpacking is a very useful feature of Python that allows us to expand either lists (using *) or dictionaries (using **). For our use case, unpacking the dictionaries splits out the key-values into separate arguments.

And we can actually do this with any number of dictionaries:

a = {'a': 1}
b = {'b': 2}
c = {'c': 3}

{**a, **b, **c}
> {'a': 1, 'b': 2, 'c': 3}

This is my preferred method, but I'll show a few more methods in the following steps.

If you're not using Python 3.5+ quite yet, there's still an easy expression to merge dictionaries:

result = dict(**address, **resident)

or slightly shorter:

result = dict(address, **resident)

The first example is very similar to step 1, so let's dissect the latter.

dict(address) creates a brand new dictionary from our existing address dict (meaning it has all of the same keys and values). But when passed kwargs, the dict class will create those key-values as well.

So what we've written above is effectively this:

result = dict(address, first_name='Leroy', last_name='Jenkins')

In the first steps, I showed how to merge dictionaries in a way that results in a new dictionary, leaving the original dictionaries intact. But maybe you're dealing with massive dictionaries or don't need to leave the original objects intact. We can merge one dictionary into another using the update method:

resident.update(address)

print(resident)
> 
{'first_name': 'Leroy',
 'last_name': 'Jenkins',
 'street': '123 W Pine St',
 'city': 'Centerville',
 'state': 'Indiana',
 'size_sq_ft': '2310'}

In this guide, I covered some of the more common (and concise) ways to merge dictionaries. Did I miss any good examples? Let me know in the comments below.

If you're interested in other dictionary-related Python content, check out my guides on nesting defaultdicts in python and using dictionary comprehensions in Python.

AKA the Walrus Operator
John John (304)
0

Many languages support assignment expressions, and with version 3.8 (PEP 572), Python is joining the party.