In Python, a dictionary is an unordered collection of data values. It stores data in the form of a key:value pair. Adding new keys to a Python dictionary is considered an essential manipulation operation in Python. Since dictionary is a mutable compound data type, programmers can easily append new keys to a dictionary. This article focuses primarily on all the different ways of adding new values to a Python dictionary.
What is adding keys to a Python Dictionary?
Dictionaries in Python are mutable. This means, you can add more keys to it. Appending more keys to an existing dictionary is called adding key to a dictionary. While using this compound data type, sometimes you have the demand to add or modify any particular key or set of keys from the key-value pairs within our dictionary. Python allows us to change the key of a dictionary using four different methods. Let us now take a look at each of them one by one.
Method 1 (a): Using the simple subscript notation:
We can add new keys to our existing Python dictionary with the help of a subscript key and the assignment operator.
dictDat = {"Python":78,"Java":26,"C#":47}
print("Dictionary before appending new keys",dictDat)
dictDat["Lua"]=16
print ("After appending a new key, the dictionary will look like:")
print(dictDat)
Output:
Dictionary before appending new keys {'Python': 78, 'Java': 26, 'C#': 47}
After appending a new key, the dictionary will look like:
{'Python': 78, 'Java': 26, 'C#': 47, 'Lua': 16}
Explanation:
In this program, we have assigned three data in the dictionary that have the keys along with them. Now, we have printed the dictionary before including any new key in it. After displaying the already-created dictionary, we have used the dictionary name along with a new “key” within the subscript and assigned a new value (that can be of any type) associating the key. Finally, we displayed the newly updated dictionary.
Method 1 (b): Using the subscript notation for adding multiple keys:
We can also include multiple keys one after another in the dictionary using the assignment operator.
Program:
dictDat={"Python":78,"Java":26,"C#":47}
print("Dictionary before appending new keys",dictDat)
dictDat["Lua"]=16
dictDat["Lisp"]=32
dictDat["Go-Lang"]=32
print ("After appending a new key, the dictionary will look like:")
print(dictDat)
Output:
Dictionary before appending new keys {'Python': 78, 'Java': 26, 'C#': 47}
After appending a new key, the dictionary will look like:
{'Python': 78, 'Java': 26, 'C#': 47, 'Lua': 16, 'Lisp': 32, 'Go-Lang': 32}
Explanation:
This program is same as the previous program except that here we have added three different keys together in three different statements and finally displayed the entire dictionary.
Method 2 (a): Using update() method:
When a Python programmer needs to add or update a lot of keys to a dictionary, they should use the built-in update() method.
Program:
dictDat={'C#':13,'Java':42}
print("Present value of Dict is:",dictDat)
dictDat.update({'MongoDB':9})
print("Updated Dictionary is:",dictDat)
Output:
Present value of Dict is: {'C#': 13, 'Java': 42}
Updated Dictionary is: {'C#': 13, 'Java': 42, 'MongoDB': 9}
Explanation:
First of all, we have created a dictDat dictionary object and stored two elements. Then, we have used the print() to display the dictionary values. Next, we have used the update() method to add another key along with the value within the previously existing dictionary. Finally, we have used the print() function again to display the updated dictionary.
Method 2 (b): Using update() method for adding multiple keys together:
We can also add multiple keys along with their values in an blank or already existing dictionary using the update() method.
Program:
dictDat={'C#':13,'Java':42}
print("Present value of Dict is:",dictDat)
dictNew={'C++':83,'Python':79}
dictDat.update(dictNew)
print(dictDat)
Output:
Present value of Dict is: {'C#': 13, 'Java': 42}
{'C#': 13, 'Java': 42, 'C++': 83, 'Python': 79}
Explanation:
First of all, we have created a dictDat dictionary object and stored two elements. Then, we have used the print() to display the dictionary values. Then, we have created a new dictionary object and assigned more keys to it. Next, we have used the update() method to passed the new dictionary as parameter to update the existing dictionary. This operation will add the keys of the new dictionary to the old dictionary. Finally, we have used the print() function again to display the updated dictionary.
Method 3: Using ** Operator:
Using the ** operator, we can also add new keys to our dictionary. In this method, you have to merge the old dictionary with the new key: value pair of another dictionary.
Program:
dictData1={"C#":"OOP","F#":"FOP","Java":"POOP"}
dictData2=dict( dictData1,**{'ForTran':'POP'})
print(dictData2)
Output:
{'C#': 'OOP', 'F#': 'FOP', 'Java': 'POOP', 'ForTran': 'POP'}
Explanation:
Here, we have created a dictionary object dictData1 and assigned few keys to it. Then we created another dictionary and assigned it with dictData1 using the dict() and passing a new key to it for adding it to another dictionary. Finally, we have used the print() function again to display the updated dictionary.
Method 4: 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 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.
Program:
dictData={'C++':'OOP','Java':'POOP'}
dictData.__setitem__('JavaScript', 'OOP')
print(dictData)
Output:
{'C++': 'OOP', 'Java': 'POOP', 'JavaScript': 'OOP'}
Explanation:
Here, we have created a dictionary object dictData and assigned few keys to it. Then we have used the dictData.__setitem__() dunter method and passed the new key to add it to the dictionary. Finally, we are printing the dictionary using the print() function.
Method 5: Using list() with .items() method:
This is another method where we can use list() and the items() method together to add new keys in the dictionary. Also, we can use the + operator to bring in new dictionary or existing dictionary.
Program:
dictData1={"ForTran":"POP","C#":"OOP","Java":"POOP"}
dictData2={5:4,4:8,2:9}
dictData1=dict( list(dictData1.items()) + list(dictData2.items()) )
print(dictData1)
Output:
{'ForTran': 'POP', 'C#': 'OOP', 'Java': 'POOP', 5: 4, 4: 8, 2: 9}
Explanation:
Here, we have created a dictionary object dictData1 and assigned few keys to it. Then we created another dictionary dictData2 and assigned few more keys and their associated values to it. Then we have applied the dictionary.items() method along with the + operator to merge two dictionaries into a single dictionary that is given in the left side of the = operator. Finally, we have used the print() function again to display the updated dictionary.
Conclusion:
Magic methods (starting & ending with two underscores) should not be preferred by the programmers directly unless they have to override the method with the same name. Dunter methods gets invoked internally from within the class depending on certain actions and circumstances. Due to condition and circumstance checks, this makes it less consistent to implement and has to qualify specific criteria to get invoked. Therefore, the most efficient way to add keys to a Python dictionary is to use the subscript technique and the update() method. Apart from that, the ** operator is also handy and easy to use. But the list() with .items() method is comparatively slower than the subscript method because it does two operations (method calls and + for merging two dictionaries) along with using two .items() methods.