Adding Key Value Pair To A Dictionary In Python

Adding Key Value Pair To A Dictionary In Python

You might have landed here while searching for an add() or append() method in Python dictionary for adding new key value pair. Yes, python dictionary does not have add() or append() method as of this writing (Python version 3.8.5). Without a specific method, how to add key value pair to a dictionary in Python? Let’s see.

You can add key value pairs to an existing dictionary by couple of methods. One is by assigning a value to key method and the other is by using the update() method. Let us see them in detail.

1. By assigning value to key

To add a new key value pair to an existing dictionary, just use the technique of assigning a value to its key. By doing so, if the key is not present in the dictionary, it will add the new key and value. If the key already exists in the dictionary, then it will update the value with the new value. The disadvantage of using this method is that, you can add only one kay value pair at a time. Here is the sample code:

# A dictionary
my_dictinary = {1: 'Tiger', 2: 'Leopard'}

print("\n", my_dictinary, "\n")

# Adding key value pair dictionary
my_dictinary[3] = 'Jaguar'

print("\n", my_dictinary, "\n")
Adding Key Value Pair To A Dictionary In Python

2. By using update() method

Another method of adding key value pairs to an existing Python dictionary is by using the update() dictionary method. Just like the previous method, if the key is not present in the dictionary, it will add the new key and value. However, if the key already exists in the dictionary then the corresponding value will be updated.Using this method, you can add multiple key value pair at the same time. Here is an example:

# A dictionary
my_dictinary = {1: 'Tiger', 2: 'Leopard'}

print("\n", my_dictinary, "\n")

# Adding key value pair dictionary
my_dictinary.update({3: 'Jaguar', 4: 'Panther'})

print("\n", my_dictinary, "\n")
Adding Key Value Pair To A Python Dictionary using update() method

Reference

Related Articles


Related Articles & Tools

Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.