How to Add New Keys to a Dictionary in Python?

In the Python programming language, dictionaries are the essential and frequently used data structure that enables users to store desired data in a key-value pair format. It contains pairs of keys and their corresponding values. While working with dictionaries, sometimes users may want to add new keys to the specific dictionary. There are multiple ways in Python to add desired keys and values in the dictionary. This article will demonstrate all the possible methods to add/insert new keys to a dictionary in Python. 

Quick Outline

  1. How to Create/Initialize a Dictionary in Python?
  2. How to Add/Insert New Keys to a Dictionary in Python?
  3. How to Delete Keys in a Python Dictionary?

How to Create/Initialize a Dictionary in Python?

To add new values in the Python dictionary, it is required to create or initialize the desired dictionary. For creating a dictionary in Python, users are required to specify the keys and their values. The keys can have integer or string data types and they must be unique. Whereas, the key values can be anything and users can repeat them. A comma “,” is used to separate each key, and a colon “:” separates each key-value pair.

For example, we are creating a “my_dict” dictionary with the following key-value pairs:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}

print("Dictionary:", my_dict)

Here: 

  • my_dict” is the name of the dictionary.
  • key1”, “key2” and “key3” are the keys.
  • Pakistan”, “Turkey”, and “Kuwait” are the corresponding values of the keys.
  • :” (colon) is utilized to pair specified keys with the values.
  • ,” (comma) is a separator for the keys/elements.
  • print()” function prints the key-value pair of the dictionary.

The below output shows that the “my_dict” dictionary has been created successfully:

Now, let’s move ahead and see how to add new keys to a Python dictionary.

How to Add/Insert New Keys to a Dictionary in Python?

Adding new keys to a dictionary means specifying new keys and their values in a Python dictionary. To add new keys to a particular dictionary in Python, various methods can be used such as:

  • Method 1: Add New Keys to Python Dictionary Using Subscript Operator
  • Method 2: Add New Keys to Python Dictionary Using “update()” Method
  • Method 3: Add New Keys to Python Dictionary Using “dict()” Constructor
  • Method 4: Add New Keys to Python Dictionary Using “**” Operator
  • Method 5: Add New Keys to Python Dictionary Using Update Operator
  • Method 6: Add New Keys to Python Dictionary Using for Loop
  • Method 7: Add New Keys to Python Dictionary Using “zip()” Method
  • Method 8: Add New Keys to Python Dictionary Using if Statement
  • Method 9: Add New Keys to Python Dictionary Using “setdefault()” Method
  • Method 10: Add New Keys to Python Dictionary Using “__setitem__” Method

Method 1: Add New Keys to Python Dictionary Using Subscript Operator

The subscript operator is basically square brackets. This method creates a new key in the specific dictionary and assigns a value to it. If the key already exists, its current value will be overwritten. 

To do so, first, create/initialize the dictionary. Here, we have created the “my_dict” dictionary. Then, use the square brackets with the existing or new key name inside them and assign values to the keys to update the value of the existing key or add a new key respectively. 

For instance, we are updating the value of the “key3” key and adding a new “key4” key:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict['key3'] = 'US'
my_dict['key4'] = 'UK'
print("\nDictionary After Adding New Keys:", my_dict)

It can be observed that the value of the “key3” key has been successfully updated and the new “key4” key has been added as seen below:

Method 2: Add New Keys to Python Dictionary Using “update()” Method

The “update()” method is used to insert new keys or elements in the Python dictionary. This method takes the keys and values as an argument and adds/inserts them into the specific dictionary. 

Here, we are adding the “newkey1” and “newkey2” keys with “Egypt” and “Saudia” values respectively in the “my_dict” dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict.update({'newkey1': 'Egypt', 'newkey2': 'Saudia'})
print("\nUpdated Dictionary: ",my_dict)

The below output indicates that the new keys have been added to the dictionary successfully:

Method 3: Add New Keys to Python Dictionary Using “dict()” Constructor

The “dict()” constructor is used to create a new object in the dictionary and enable users to add new keys. This method takes the specific dictionary and the new desired key and value as an argument to add it to the dictionary.

For instance, we are adding a new “key4” key with the value “SriLanka” in the “my_dict” dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict = dict(my_dict, key4 = 'SriLanka')
print("\nUpdated Dictionary:", my_dict)

According to the below screenshot, the “key4” key has been added to a dictionary:

Method 4: Add New Keys to Python Dictionary Using “**” Operator

The “**” operator (unpacking operator) is also utilized to add new keys to a particular dictionary in Python. In this method, users create a new dictionary with one key-value pair and merge it with the desired dictionary using the “**” operator to unpack their key-value pairs. 

Here, we have a “my_dict” dictionary and we will create a new “new_dict” dictionary with a new key and value. Both dictionaries will be merged using the “**” operator:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

new_dict = {**my_dict, **{'newkey': 'India'}}
print("\nUpdated Dictionary:", new_dict)

It can be observed that the new key has been successfully added to the original dictionary as seen below:

Method 5: Add New Keys to Python Dictionary Using Update Operator

Users can also use the update (|=”) operator instead of the “update()” method to add the new desired keys to a specific dictionary in Python.

For instance, we are adding the “newkey1” and “newkey2” keys with “Iran” and “165” values respectively in the “my_dict” dictionary: 

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict |= {'newkey1': 'Iran', 'newkey2': 165}
print("\nUpdated Dictionary:", my_dict)

According to the below output, the new keys have been added to the dictionary:

Method 6: Add New Keys to Python Dictionary Using for Loop

The for loop is utilized to iterate over a specific sequence. Users can use the for loop to add new keys to the dictionary by iterating it over given values and adding them to the desired dictionary.

Here, we are adding two keys “newkey1” and “newkey2” with corresponding values “India” and “Iran” respectively to the “my_dict” dictionary using for loop:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

new_val = [('newkey1', 'India'), ('newkey2', 'Iran')]
for key, value in new_val:
    my_dict[key] = value
print("\nUpdated Dictionary:", my_dict)

By doing so, the values have been added to the dictionary as seen below:

Method 7: Add New Keys to Python Dictionary Using “zip()” Method

The “zip()” method can also be utilized in the for loop to add multiple keys and values to the Python dictionary. This method takes multiple iterables as an argument and adds/merges each of their values. Then it returns a zip object that is an iterator and contains tuples. 

For instance, we are specifying some keys i.e. “key4”, “key5” and “key6” and values i.e. “US”, “UK” and “Canada” and passing them in the “zip()” function as arguments. These keys and values will be merged and added to the “my_dict” dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

keys = ['key4', 'key5', 'key6']
values = ['US', 'UK', 'Canada']

for key, value in zip(keys, values):
    my_dict[key] = value
print("\nUpdated Dictionary:", my_dict)

In the below output, it can be seen that the new keys have been added to the desired dictionary successfully:

Method 8: Add New Keys to Python Dictionary Using if Statement

The if statement can also be utilized to add the specific key to the Python dictionary if it is not already present in it. If the key already exists, it will display the desired message. 

Here, we are adding the “key4” key along with its value i.e. “SriLanka” to the “my_dict” dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

if "key4" not in my_dict:
    my_dict["key4"] = "SriLanka"
else:
    print("key already exists in the Dictionary")

print("\nUpdated Dictionary:", my_dict)

As the “key4” key was not present in the dictionary, it has been added to it as seen below: 

Method 9: Add New Keys to Python Dictionary Using “setdefault()” Method

The “setdefault()” method is the easiest way to add new desired keys to the dictionary without overwriting the already present keys. This method takes two arguments. The first argument is the desired key that needs to be added and the second argument is the specific value for the key.

For instance, we are adding a new key i.e. “key4” with a value “Saudi Arabia” to the dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict.setdefault('key4', 'Saudi Arabia')
print("\nUpdated Dictionary:", my_dict)

The below output indicates that the new “key4” key has been added to the dictionary:

Method 10: Add New Keys to Python Dictionary Using “__setitem__” Method

The “__setitem__” method can also be used to add a particular key-value pair to the desired dictionary. However, it is not an efficient way due to its poor performance.

Here, we are adding the new “key4” key using the “__setitem__” method in the “my_dict” dictionary:

my_dict = {'key1' : 'Pakistan', 'key2' : 'Turkey', 'key3' : 'Kuwait'}
print("Original Dictionary:", my_dict)

my_dict.__setitem__('key4', 'Malaysia')
print("\nUpdated Dictionary:", my_dict)

As you can see in the below screenshot, the new key has been added to the dictionary:

How to Delete Keys From a Python Dictionary?

Sometimes, users may want to delete or remove specific keys from the Python dictionary that they do not need anymore. To delete keys/elements from a dictionary, different methods are used, such as:

  • Method 1: Delete Keys/Elements From the Dictionary Using the “del” Keyword
  • Method 2: Delete Keys/Elements From the Dictionary Using “pop()” Method

Method 1: Delete Keys/Elements From the Dictionary Using the “del” Keyword

The “del” keyword removes/deletes the specific key from the Python dictionary. To do so, utilize the “del” keyword along with the dictionary name and specify the desired key name that needs to be deleted.

The below output shows the dictionary that has three keys. For instance, we want to delete the “key2” key:

To delete the “key2” key, use the “del” keyword and specify the dictionary name and the selected key to delete it. Then, print the dictionary elements:

del my_dict['key2']

print("Dictionary after deleting key:", my_dict)

By doing that, the “key2” key has been deleted as seen below:

Method 2: Delete Keys/Elements From the Dictionary Using “pop()” Method

The “pop()” method takes the name of the specific key that needs to be removed or deleted from the dictionary as an argument. 

For instance, we are deleting the “key3” key from the “my_dict” dictionary:

my_dict.pop('key3')

print("Dictionary after deleting key:", my_dict)

It can be seen that the “key3” key has been deleted successfully from the dictionary:

Note: Click on the provided link to access Google Colab Notebook. 

Bottom Line

In Python, various methods can be used to add/insert new keys to the specific dictionary. Users can add one or multiple keys to the Python dictionary using subscript, “**”, and update operators or using the “update()”, “dict()”, “zip()”, “setdefault()”, and “__setitem__” methods. Moreover, users can also use for loop or if statements to perform this operation. The subscript operator and “update()” methods are the easiest and simplest methods to add new keys to the specific dictionary. This article has demonstrated the method of creating a dictionary, all the possible ways to add new keys to a dictionary, and the methods of deleting specific keys from the dictionary in Python.