Tutorials  /  Python

How To Add to a Dictionary in Python: Step-by-Step Guide

Ccentron Redaktion · December 2024 ·6 min read ·Python, Tutorial

Dictionary is a built-in Python data type. A dictionary is a sequence of key-value pairs. Dictionaries are mutable objects, however, dictionary keys are immutable and need to be unique within each dictionary. There’s no built-in add method, but there are several ways to add to and update a dictionary. In this article, you’ll use the Python assignment operator, the update() method, and the merge and update dictionary operators to add to and update Python dictionaries.

VM

Try it yourself: cloud servers from €3.12/month

ccloud³ VMs from German data centers – deployed in seconds, billed by the hour, with a €200 starting credit for new accounts. Launch a server →

Four Methods to Add to the Dictionary

  • Using the Assignment Operator
  • Using the Update Method
  • Using the Merge Operator
  • Using the Update Operator

Add to Python Dictionary Using the = Assignment Operator

You can use the = assignment operator to add a new key to a dictionary:

Code
dict[key] = value

If a key already exists in the dictionary, then the assignment operator updates, or overwrites, the value.

The following example demonstrates how to create a new dictionary and then use the assignment operator = to update a value and add key-value pairs:

Python
dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

Output:

Code
Output
original dictionary:  {'a': 1, 'b': 2}
updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4}

The output shows that the value of a is overwritten by the new value, the value of b is unchanged, and new key-value pairs are added for c and d.

Add to Dictionary Without Overwriting Values

Using the = assignment operator overwrites the values of existing keys with the new values. If you know that your program might have duplicate keys, but you don’t want to overwrite the original values, then you can conditionally add values using an if statement.

Continuing with the example from the preceding section, you can use if statements to add only new key-value pairs to the dictionary:

Python
dict_example = {'a': 1, 'b': 2}

print("original dictionary: ", dict_example)

dict_example['a'] = 100  # existing key, overwrite
dict_example['c'] = 3  # new key, add
dict_example['d'] = 4  # new key, add 

print("updated dictionary: ", dict_example)

# add the following if statements

if 'c' not in dict_example.keys():
    dict_example['c'] = 300

if 'e' not in dict_example.keys():
    dict_example['e'] = 5

print("conditionally updated dictionary: ", dict_example)

This is the output:

Code
Output
original dictionary:  {'a': 1, 'b': 2}
updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4}
conditionally updated dictionary:  {'a': 100, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

The output shows that, because of the if condition, the value of c didn’t change when the dictionary was conditionally updated.

Add to Python Dictionary Using the update() Method

You can append a dictionary or an iterable of key-value pairs to a dictionary using the update() method. The update() method overwrites the values of existing keys with the new values.

The following example demonstrates how to create a new dictionary, use the update() method to add a new key-value pair and a new dictionary, and print each result:

Python
site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary'}
print("original dictionary: ", site)

# update the dictionary with the author key-value pair
site.update({'Author':'Sammy Shark'})
print("updated with Author: ", site)

# create a new dictionary
guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

# update the original dictionary with the new dictionary
site.update(guests)
print("updated with new dictionary: ", site)

Output:

Code
Output
original dictionary:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary'}
updated with Author:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark'}
updated with new dictionary:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy Shark', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

The output shows that the first update adds a new key-value pair and the second update adds the key-value pairs from the guest dictionary to the site dictionary. Note that if your update to a dictionary includes an existing key, then the old value is overwritten by the update.

Add to Dictionary Using the Merge | Operator

You can use the dictionary merge | operator, represented by the pipe character, to merge two dictionaries and return a new dictionary object.

The following example demonstrates how to create two dictionaries and use the merge operator to create a new dictionary that contains the key-value pairs from both:

Python
site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

new_site = site | guests

print("site: ", site)
print("guests: ", guests)
print("new_site: ", new_site)

Output:

Code
Output
site:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy'}
guests:  {'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}
new_site:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

Two dictionaries were merged into a new dictionary object that contains the key-value pairs from both dictionaries.

If a key exists in both dictionaries, then the value from the second dictionary, or right operand, is the value taken. In the following example code, both dictionaries have a key called b:

Python
dict1 = {'a':'one', 'b':'two'}
dict2 = {'b':'letter two', 'c':'letter three'}

dict3 = dict1 | dict2

print("dict3: ", dict3)

The is the output:

Code
Output
dict3:  {'a': 'one', 'b': 'letter two', 'c': 'letter three'}

The value of key b was overwritten by the value from the right operand, dict2.

Add to Python Dictionary Using the Update |= Operator

You can use the dictionary update |= operator, represented by the pipe and equal sign characters, to update a dictionary in-place with the given dictionary or values.

Just like the merge | operator, if a key exists in both dictionaries, then the update |= operator takes the value from the right operand.

The following example demonstrates how to create two dictionaries, use the update operator to append the second dictionary to the first dictionary, and then print the updated dictionary:

Python
site = {'Website':'DigitalOcean', 'Tutorial':'How To Add to a Python Dictionary', 'Author':'Sammy'}

guests = {'Guest1':'Dino Sammy', 'Guest2':'Xray Sammy'}

site |= guests

print("site: ", site)
Code
Output
site:  {'Website': 'DigitalOcean', 'Tutorial': 'How To Add to a Python Dictionary', 'Author': 'Sammy', 'Guest1': 'Dino Sammy', 'Guest2': 'Xray Sammy'}

In the preceding example, you didn’t need to create a third dictionary object. Because the update operator modifies the original object. The output shows that the guests dictionary was appended to the original site dictionary.

Conclusion

In this article, you used different methods to add to and update a Python dictionary. These methods include the assignment operator, the update() method, the merge operator (|), and the update operator (|=). Each of these techniques has its specific use cases. It allows you to effectively handle scenarios like adding new key-value pairs, merging dictionaries, or conditionally updating existing values.

Understanding these methods provides flexibility and efficiency in managing Python dictionaries, which are an essential part of Python programming. Whether you're working on a small script or a complex application, mastering these approaches will enhance your ability to handle data and optimize your code.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Python
Teilen
Noch offene Fragen?

Unser Team hilft Ihnen bei Ihrem konkreten Setup weiter – von Menschen, die die Plattform selbst betreiben.

War dieses Tutorial hilfreich?

Ihre Antwort wird anonym gespeichert und hilft uns, die Tutorials zu verbessern.

Kommentare

Noch keine Kommentare – stellen Sie die erste Frage zu diesem Tutorial.

Zum Kommentieren anmelden

Kommentare stehen centron-Kunden offen. Melden Sie sich in Ihrem Konto an, um eine Frage zu diesem Tutorial zu stellen.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren