In Python, a dictionary is an unordered collection of data values. It stores data in the form of a key:value pair. Adding values to a Python dictionary is essential to know for Python programmers. This article focuses primarily on all the different ways of adding new values to a Python dictionary.
What You Mean by Adding Values to a Python Dictionary?
Appending more values to an existing dictionary is called adding value to a dictionary. While using a dictionary, sometimes we need to add or modify a few data/values in the key/value within our dictionary. Python allows us to do this using five different approaches.
Create a Dictionary:
Before adding new values, let us first create an empty dictionary. There are two ways of doing that.
dictData = {}
dictData = dict()
1. Using dict[key] = value
We can add new values to the existing dictionary using a new key and the assignment operator.
Code Example:
dictData = {"Python": 62, "C++" : 36 , "JavaScript" : 18}
print('Original dictionary: ', dictData)
# New Value
dictData["HTML"] = 22
dictData["CSS"] = 10
print ("Adding a new value, the dictionary looks like: ", dictData)
Output:
Original dictionary: {'Python': 62, 'C++': 36, 'JavaScript': 18}
Adding a new value, the dictionary looks like: {'Python': 62, 'C++': 36, 'JavaScript': 18, 'HTML': 22, 'CSS': 10}
Code Explanation:
In this program, we have assigned three data within our dictionary with their respective keys. Now, after displaying the already-created dictionary, we planned to add another “key : value” pair. We have used the assignment operator and put another value that got assigned to our new key.
2. Using Subscript notation:
This method will produce a new value on a dictionary by allocating a value with your dictionary's key. If the key does not exist in your existing dictionary, it will add and allocate the value with it. If the key exists with a value, adding a new value will overwrite its old value.
dictData['new key'] = 'new value'
dictData now becomes:
{'new key' : 'new value'}
Code Example:
dictData = {"a": [1, 3], "b": [4, 6]}
print('Original dictionary: ',dictData)
dictData["c"] = [7, 9]
print('After Update: ',dictData)
Output:
Original dictionary: {'a': [1, 3], 'b': [4, 6]}
After Update: {'a': [1, 3], 'b': [4, 6], 'c': [7, 9]}
3. Using dict.update():
When Python programmers need to update a great collection of values in a dictionary, they prefer to use the update() method. There are two different ways of using the update() method. We can also add multiple key:value pairs with our update() method.
a) Using the key: value pair directly as dictionary
dictData = {'key1' : 'val1', 'key2' : 'val2'}
print("Original Dictionary is: ", dictData)
# We can directly add a new dictionary within the update()
dictData.update({'key3' : 'val3'})
print("Updated Dictionary by Single dictionary: ", dictData)
# We can create another separate dictionary and put new values and then update()
dictData2 = {'key4' : 'value4', 'key5' : 'value5'}
dictData.update(dictData2)
print("Updated Dictionary with multiple values is: ",dictData)
Output:
Orignal Dictionary is: {'key1': 'val1', 'key2': 'val2'}
Updated Dictionary by Single dictionary: {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}
Updated Dictionary with multiple values is: {'key1': 'val1', 'key2': 'val2', 'key3': 'val3', 'key4': 'value4', 'key5': 'value5'}
b) Using the argument form:
Another significant and efficient way of updating or adding new value is using the arguments as key = value within the update().
Example1:
dictData = {'key4' : 'value4', 'key5' : 'value5'}
print('Original dictionary: ',dictData)
dictData.update(newkey1 = 'newVal1')
print('Dictionary after update: ',dictData)
Output:
Original dictionary: {'key4': 'value4', 'key5': 'value5'}
Dictionary after update: {'key4': 'value4', 'key5': 'value5', 'newkey1': 'newVal1'}
Example 2:
# Python program to add multiple values in dictionary
dictData = {'key4' : 'value4', 'key5' : 'value5'}
print('Original dictionary: ',dictData)
dictData1 = {'key6' : 'value6', 'key7' : 'value7'}
dictData.update(dictData1)
print('Dictionary after update: ',dictData)
Output:
Original dictionary: {'key4': 'value4', 'key5': 'value5'}
Dictionary after update: {'key4': 'value4', 'key5': 'value5', 'key6': 'value6', 'key7': 'value7'}
4)Using * Operator:
Using the * operator, we can also add new values to our dictionary. In this method, you have to merge the old dictionary with the new key: value pair of another dictionary.
Example1:
# Original dictionary
dictData1 = {"C":"POP", "F#":"FOP", "Java":"POOP"}
print('Original dictionary',dictData1)
# Create new dictionary by adding new and value pair to dictionary
dictData2 = dict(dictData1, **{'C++':'OOP'})
print('New dictionary:',dictData2)
Output:
Original dictionary {'C': 'POP', 'F#': 'FOP', 'Java': 'POOP'}
New dictionary: {'C': 'POP', 'F#': 'FOP', 'Java': 'POOP', 'C++': 'OOP'}
Example 2:
# Python program to add multiple values in dictionary
# Original dictionary
dictData1 = {"C":"POP", "F#":"FOP", "Java":"POOP"}
print('Original dictionary',dictData1)
dictData2 = {"PHP":"POP", "PYTHON":"OOP", "Java":"POOP"}
# Create new dictionary by adding new and value pair to dictionary
dictData1 = dict(dictData1, **dictData2)
print('New dictionary:',dictData1)
Output:
Original dictionary {'C': 'POP', 'F#': 'FOP', 'Java': 'POOP'}
New dictionary: {'C': 'POP', 'F#': 'FOP', 'Java': 'POOP', 'PHP': 'POP', 'PYTHON': 'OOP'}
5. Using list() and .items() method:
This is another method where we can use list() and the items() method within it to append new values in the dictionary. Also, we can use the + operator to bring in the new dictionary or existing dictionary. Here is a code snippet showing how to use them to
Example:
dictData1 = {"C" : "POP", "F#" : "FOP", "Java" : "POOP"}
dictData2 = {2:2, 3:3, 4:4}
dictData1 = dict( list(dictData1.items()) + list(dictData2.items()) )
print(dictData1)
Output:
{'C': 'POP', 'F#': 'FOP', 'Java': 'POOP', 2: 2, 3: 3, 4: 4}
6. Using for loop within dict():
Using loops within the dict() we can bring in multiple dictionary value from other dictionary and include them within our old dictionary.
dictData1 = {"C" : "POP", "F#" : "FOP", "Java" : "POOP"}
print('Dictionary One: ',dictData1)
dictData2 = {2:2, 3:3, 4:4}
print('Dictionary Two: ',dictData2)
# Add value in dictionary using loop
dictdata3 = dict( i for dictData2 in [dictData1, dictData2] for i in dictData2.items() )
print('Dictionary after adding value: ',dictdata3)
Adding Values in dictionary using Merge Operator:
Python 3.9 introduced the new merge operator (|) and update (|=) operators as a part of the built-in dict class. | is also called the dictionary union operator. It returns a new dictionary merging the left operand with the right operand where both the operand has to be a dictionary. The update (|=) operator will return the left operand merged with the right. It acts as a shorthand operator for the merge operator.
Here is a code snippet showing the use of both.
dictData1 = {'g': 10, 'k': 5, 'r': 3}
dictData2 = {'s': 6, 'u': 4, 'e': 8}
dictData3 = dictData1 | dictData2
print("Merging both the dictionary using Merge Operator, we get : ")
print(dictData3)
dictData1 |= dictData2
print("\n Merging second dictionary to the first one and Update the first dictionary : ")
print("dict1 : " + dictData1)
print("dict2 : " + dictData2)
8. Using __setitem__():
Python allows its programmers to use some special methods that start and end with the double underscores. Such methods are also known as dunter methods. We do not invoke the magic methods directly. The invocation takes place internally from the class based on some specific action. __setitem__() method is also a magic method used to add a key-value pair to the dict.
Note that, you can avoid using this method because it has poor performance as compared to other methods listed in this article.
Example1:
dictData = {'C++' : 'OOP', 'Java' : 'POOP'}
print('Original dictionary: ',dictData)
dictData.__setitem__('JavaScript', 'OOP')
print('New dictionary: ',dictData)
Output:
Original dictionary: {'C++': 'OOP', 'Java': 'POOP'}
New dictionary: {'C++': 'OOP', 'Java': 'POOP', 'JavaScript': 'OOP'}
Why Avoid Magic Method?
We have to call the magic methods (starting & ending with two underscores) directly unless you have to override a method with the same name. Such method invocation takes place internally from within the class based on certain actions or situations. That makes it less consistent to implement within a Python program as the program has to meet the specific condition to invoke such methods.
Also, using a magic method reduces the performance of the program. Programmers do not create magic methods to call them directly. Rather, programmers internally call them with the help of some other actions or methods. This makes the process and program execution slower.
Conclusion:
- We can say that each of these mentioned methods has its benefits and drawbacks. Using update(), * operator, list() items(), and for loop technique, we can add multiple values to our dictionary. To add multiple values with other methods, we have to repeat the statement multiple times for adding a new key:value.
- Adding values using assignment operator and subscript method works faster than other methods and hence used and preferred by most programmers.
- Professional programmers do not prefer __setitem__() magic method for adding values in Python because its invocation takes place implicitly from the class when it encounters certain actions or situations.
- In method 6, i.e. using for loop within the dict() is easy to implement and is preferred when programmers need to write large automation code. But, this method has a drawback. It will create a time complexity of O(n^2).