Merging Django contexts: merge dicts in Python

While developing web apps for Django you will eventually need to join more than one dictionary together. This is because Django uses dictionaries to define the context for template rendering. But what is the case you would need to join a dictionary instead of just creating one in place?

The most common use case I encounter is when you have a dynamic common set of elements, such as a navigation bar or a footer, that appear on every page you render. In this case, for each page to be rendered, the context of the common elements and the context for the specific page will be needed. You will therefore need to combine multiple dictionaries.

Python offers multiple ways to combine multiple dictionaries. Let's quickly guide you through some of them.

Using ** operator

I consider this to be the easiest method yet it's considered to be a hack. The double-star operator is a way to pass multiple arguments into a function directly using a dictionary.

common_context = {'site_name': 'Hello world site'}
page_context = {**common_context, 'page_specific_element': 'Welcome!'}

Using | operator

This was added to Python 3.9. Using the "|" operator 2 dictionaries can be merged together conveniently.

common_context = {'site_name': 'Hello world site'}
page_context = common_context | {'page_specific_element': 'Welcome!'}

Using update() method

After the execution of the following snippet the page_context variable holds a dictionary with the merged key-value pairs. Note that the result of the update() call is None so you can't use the method call directly in a return call.

common_context = {'site_name': 'Hello world site'}
page_context = {'page_specific_element': 'Welcome!'}
page_context.update(common_context)

There are a few more ways to merge dictionaries, such as the manual way of iterating through one dictionary and adding key-value pairs to the other, but I think the mentioned methods are more than enough to choose from. Hopefully, you can now have one less thing to worry about when rendering your templates in Django.

Happy coding!