How To Add New Keys To a Python Dictionary?

Introduction

Before diving into the solutions to our question, here’s a quick recap of Python dictionaries.

In Python, a dictionary is a collection of objects. A Python dictionary stores data in the form of key-value pairs. A dictionary in Python is ordered, changeable and does not allow duplicates. The keys in the dictionary are paired with the values by using a colon (:) while the commas fill in as a separator for the pairs. The values can be the same but the keys have to be unique in a dictionary.

? Note: From Python 3.7, dictionaries are ordered. However, in Python3.6 and earlier, dictionaries are unordered.

Example:

names_and_countries = {'Chris': 'Germany',
                       'Beth': 'Bulgaria',
                       'Rashi': 'India',
                       'Dani': 'Denmark',
                       'Shubham': 'Australia'}

Recommended Tutorial: Python Dictionary โ€“ The Ultimate Guide

Now that you have an idea about the dictionary data structure in Python, let us dive into our mission-critical question – “How to add new keys to a Python Dictionary?”

โ– Problem Formulation

Given a dictionary with key-value pairs. You have been asked to add another key to this dictionary. How would you do this?  

As dictionaries are mutable, we can add and delete the items inside them. In this article, we are going to learn to add new keys to a dictionary in Python.

Example:

d = {"Python": 1, "Java": 4}
print("Original Dictionary: ", d)
d["C#"] = 3
print("After adding a key:")
print(d)

Output:

Original Dictionary:  {'Python': 1, 'Java': 4}
After adding a key:
{'Python': 1, 'Java': 4, 'C#': 3}

Now, let’s dive into the methods that will demonstrate how to add new keys to the dictionary.

โœ๏ธMethod 1: Subscript Notation

You can add any key inside the dictionary and assign a value to it using the subscript (square-bracket) notation []. If the key is already present inside the dictionary, it will overwrite the original value with the new value.

Example:

d = {"Python": 1, "Java": 4}
print("Original Dictionary: ", d)

# Adding a new key
d["C#"] = 3
print("After adding a key:", d)

# Assigning a new value to an existing key
d["Python"] = 2
print("After changing the value:", d)

Output:

Original Dictionary:  {'Python': 1, 'Java': 4}
After adding a key: {'Python': 1, 'Java': 4, 'C#': 3}
After changing the value: {'Python': 2, 'Java': 4, 'C#': 3}

You can also add a key with no value in a dictionary. To do this, you have to assign “None” as the value to the key.

Example:

d = {"Python": 1, "Java": 4}
print("Original Dictionary: ", d)

# Adding a new key with None value
d["C#"] = None
print("After adding a key with NONE as the value: ", d)

Output:

Original Dictionary:  {'Python': 1, 'Java': 4}
After adding a key with NONE as the value:  {'Python': 1, 'Java': 4, 'C#': None}

โœ๏ธMethod 2: Using The Update() Method

In Python, we can use the update() method to add keys to an existing dictionary. The update() method takes two arguments (key and value) and then updates the dictionary with the new key-value pairs. Similar to the previous method, if the key is present in the dictionary, it gets overwritten with the new value.

Syntax:

dict.update( {โ€˜keyโ€™: value} )

Example:

# Given a dictionary with two key-value pairs
d = {"Python": 1, "Java": 4}
print("Original dictionary: ", d)

# Adding a new key using update()
d.update({'Ruby': 7})
print("After adding a key:", d)

# Assigning a new value to an existing key
d.update({'Java': 8})
print("After changing the value:", d)

Output:

Original dictionary:  {'Python': 1, 'Java': 4}
After adding a key: {'Python': 1, 'Java': 4, 'Ruby': 7}
After changing the value: {'Python': 1, 'Java': 8, 'Ruby': 7}

We can also add multiple keys in a dictionary simultaneously using the update() method as shown in the following example.

Example:

d = {"Python": 1, "Java": 4}
print("Original Dictionary: ", d)

# Adding multiple keys using update() method
d.update([('Ruby', 3), ('C++', 7), ('Python', 5)])
print("After adding multiple keys:", d)

Output:

Original Dictionary:  {'Python': 1, 'Java': 4}
After adding multiple keys: {'Python': 5, 'Java': 4, 'Ruby': 3, 'C++': 7}

โœ๏ธMethod 3: Using the Merge and Update Operators

We can merge the two dictionaries by using either the update operator or the merge operator.

  • The Merge operator (|) is used to combine the keys and values of both the given dictionaries and then stored in a new dictionary.
    • It can be viewed as d3 = d2+d1.
  • The Update operator (|=) is used to update the key-value pairs of one dictionary into another existing dictionary.
    • It can be viewed as d1 = d1+d2.

?Caution: You must have Python Version 3.9 or higher in order to use the merge operator.

Example:

dict1 = {"Python": 1, "Java": 4}
dict2 = {"Ruby": 3, "C#": 2}

# Merging the dictionaries using Merge operator
dict3 = dict1 | dict2
print("After using merge operator dict3:")
print(dict3)

# Merging the dictionaries using Update operator
dict1 |= dict2
print("After using update operator dict1:")
print(dict1)

Output:

After using merge operator dict3:
{'Python': 1, 'Java': 4, 'Ruby': 3, 'C#': 2}
After using update operator dict1:
{'Python': 1, 'Java': 4, 'Ruby': 3, 'C#': 2}

โœ๏ธMethod 4: Using ** Operator

In Python, the ** operator is used to add key-value pairs into the dictionary. The operator merges these pairs with the existing dictionary.

Here’s a comprehensive tutorial on Python’s double-asterisk operator Python Double Asterisk (**)

Now let us have a quick look at how the double asterisk operator can help us to add keys to a dictionary with the help of an example.

d = {"Python": 1, "Java": 4}
print("Original Dictionary:", d)

# Adding a key in new dictionary and merging it with the existing dictionary
dict2 = {**d, **{'Ruby': 3}}
print("After adding new key:", dict2)

Output:

Original Dictionary: {'Python': 1, 'Java': 4}
After adding new key: {'Python': 1, 'Java': 4, 'Ruby': 3}

Conclusion

Therefore, in this article, you learned about the various methods that can be used to add new keys to a dictionary in Python. To keep learning, please subscribe to our channel and blog tutorials and stay tuned for more interesting tutorials.

Related Tutorial: How to Append Values to Dictionary in Python

๐Ÿ‘‰ Recommended: Python Dictionary Append โ€“ 4 Best Ways to Add Key/Value Pairs

โœ Post Credits: Shubham Sayon and Rashi Agarwal


  • Do you want to master the most popular Python IDE fast?
  • This course will take you from beginner to expert in PyCharm in ~90 minutes.
  • For any software developer, it is crucial to master the IDE well, to write, test and debug high-quality code with little effort.
The Complete Guide to PyCharm

Join the PyCharm Masterclass now, and master PyCharm by tomorrow!