DEV Community

Harlin Seritt
Harlin Seritt

Posted on

Concatenating Python Dictionaries

When I'm working with Django I often like to create a base context which is a Python dict for a set of views and initially define them outside of each view. Within each view, instead of creating a new context, I prefer to update the context.

So, with Python, you can combine two dictionaries in a couple of different ways. Here are two methods:

Using update() Method:

You can think of dictionaries in Python like collections of information. Let's say you have two dictionaries, each with some details:

Dictionary 1: It contains information about a person named Sarah, like her age (15) and the number of books she has (3).

Dictionary 2: Now, you want to add more information to Dictionary 1, like Sarah's new age (16) and the fact that she got a new bicycle.

When you use the update() method, it's like taking the information from Dictionary 2 and adding it to Dictionary 1:

dict1 = {'app_name': 'MyApp', 'def_page_title': 'Welcome to MyApp'}
dict2 = {'objects': MyModel.objects.filter(is_active=True)}

dict1.update(dict2)

print(dict1)
Enter fullscreen mode Exit fullscreen mode

The result will be:

{
    'app_name': 'MyApp',
    'def_page_title': 'Welcome to MyApp',
    'objects': MyModel.objects.filter(is_active=True)
}
Enter fullscreen mode Exit fullscreen mode

Using the Unpacking Operator (**):

You can also use the ** operator.

Let's use a simple example.

Imagine you have two sets of information about a person named David:

Set 1: It mentions David's favorite color (blue) and the number of pets he has (2 cats).

Set 2: Now, you want to combine Set 1 and Set 2 into a single set of information.

You can do this using the unpacking operator (**), which creates a new set of information by putting together everything from both sets:

set1 = {'color': 'blue', 'pets': '2 cats'}
set2 = {'color': 'green', 'hobby': 'playing chess'}

combined_set = {**set1, **set2}

print(combined_set)
Enter fullscreen mode Exit fullscreen mode

The result will be:

{'color': 'green', 'pets': '2 cats', 'hobby': 'playing chess'}
Enter fullscreen mode Exit fullscreen mode

In both cases, you're adding or merging information to create a more complete set of details, just like updating or combining facts about a person. Both ways work the same. But for me using {...}.update({...}) seems more readable.

Top comments (0)