Merge dictionaries in Python

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',
}
1

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.

2

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')
3

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'}
4

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 if the comments below.