A Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is provided in the dictionary to make it more optimized. A colon separates each key-value pair in a Dictionary: whereas each key is separated by a ‘comma’. The keys of a Dictionary must be unique and of immutable data types such as Strings, Integers, and tuples, but the key values can be repeated and be of any type. In this article, we will cover how to add to a Dictionary in Python.
Python Program to Add Keys to a Dictionary
There are various methods to add to dictionary in Python here we explain some generally used methods for add to dict in Python which are the following.
- Using Subscript notation
- Using update() Method
- Using __setitem__ Method
- Using the ** operator
- Using If statements
- Using enumerate() Method
- Using Zip
- Using a Custom Class
- Using Merge | Operator
Add to a Dictionary in Python using the Subscript Notation
This method will create a new key\value pair on a dictionary by assigning a value to that key. If the key doesn’t exist, it will be added and point to that value. If the key exists, its current value will be overwritten.
Python3
dict = {'key1': 'geeks', 'key2': 'fill_me'}
print("Current Dict is:", dict)
dict['key2'] = 'for'
dict['key3'] = 'geeks'
print("Updated Dict is:", dict)
|
Output
Current Dict is: {'key1': 'geeks', 'key2': 'fill_me'}
Updated Dict is: {'key1': 'geeks', 'key2': 'for', 'key3': 'geeks'}
Add to a Dictionary in Python using update() Method
When we have to update/add a lot of keys/values to the dictionary, the update() method is suitable. The update() method inserts the specified items into the dictionary.
Python3
dict = {'key1': 'geeks', 'key2': 'for'}
print("Current Dict is:" , dict)
dict.update({'key3': 'geeks'})
print("Updated Dict is:", dict)
dict1 = {'key4': 'is', 'key5': 'fabulous'}
dict.update(dict1)
print("After adding dict1 is:" , dict)
dict.update(newkey1='portal')
print("After asssigning new key:" , dict)
|
Output :
Current Dict is: {'key1': 'geeks', 'key2': 'for'}
Updated Dict is: {'key1': 'geeks', 'key2': 'for', 'key3': 'geeks'}
After adding dict1 is: {'key1': 'geeks', 'key2': 'for', 'key3': 'geeks', 'key4': 'is', 'key5': 'fabulous'}
After asssigning new key: {'key1': 'geeks', 'key2': 'for', 'key3': 'geeks', 'key4': 'is', 'key5': 'fabulous', 'newkey1': 'portal'}
Add to Dict in Python using the __setitem__ Method
The __setitem__ method to add a key-value pair to a dict using the __setitem__ method. It should be avoided because of its poor performance (computationally inefficient).
Python3
dict = {'key1': 'geeks', 'key2': 'for'}
dict.__setitem__('newkey2', 'GEEK')
print(dict)
|
Output :
{'key1': 'geeks', 'key2': 'for', 'newkey2': 'GEEK'}
Add to Dict in Python using the ** Operator
We can merge the old dictionary and the new key/value pair in another dictionary. Using ** in front of key-value pairs like **{‘c’: 3} will unpack it as a new dictionary object.
Python3
dict = {'a': 1, 'b': 2}
new_dict = {**dict, **{'c': 3}}
print(dict)
print(new_dict)
|
Output :
{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3}
Add New Keys to a Dictionary using the “in” operator and IF statements
If the key is not already present in the dictionary, the key will be added to the dictionary using the if statement. If it is evaluated to be false, the “Dictionary already has a key” message will be printed.
Python3
mydict = {"a": 1, "b": 2, "c": 3}
if "d" not in mydict:
mydict["d"] = "4"
else:
print("Dictionary already has key : One. Hence value is not overwritten ")
print(mydict)
|
Output :
{'a': 1, 'b': 2, 'c': 3, 'd': '4'}
Add to a Dictionary in Python using enumerate() Method
Make a list of elements. Use the enumerate() method to iterate the list, and then add each item to the dictionary by using its index as a key for each value.
Python3
list1 = {"a": 1, "b": 2, "c": 3}
list2 = ["one: x", "two:y", "three:z"]
for i, val in enumerate(list2):
list1[i] = val
print(list1)
|
Output :
{'a': 1, 'b': 2, 'c': 3, 0: 'one: x', 1: 'two:y', 2: 'three:z'}
Add Multiple Items to a Python Dictionary with Zip
In this example, we are using a zip method of Python for adding keys and values to an empty dictionary python. You can also use an in the existing dictionary to add elements in the dictionary in place of a dictionary = {}.
Python3
dictionary = {}
keys = ['key2', 'key1', 'key3']
values = ['geeks', 'for', 'geeks']
for key, value in zip(keys, values):
dictionary[key] = value
print(dictionary)
|
Output :
{'key2': 'geeks', 'key1': 'for', 'key3': 'geeks'}
Add New Keys to a Dictionary with a Custom Class
At first, we have to learn how can we create dictionaries using Python. It defines a class called my_dictionary that inherits from the built-in dict class. The class has an __init__ method that initializes an empty dictionary, and a custom add method that adds key-value pairs to the dictionary.
Python3
class my_dictionary(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
dict_obj = my_dictionary()
dict_obj.add(1, 'Geeks')
dict_obj.add(2, 'forGeeks')
print(dict_obj)
|
Output :
{1: 'Geeks', 2: 'forGeeks'}
Add New Keys to a Dictionary using the Merge | Operator
In this example the below Python code adds new key-value pairs to an existing dictionary using the `|=` merge operator. The `my_dict` dictionary is updated to include the new keys and values from the `new_data` dictionary.
Python3
my_dict = {'name': 'John', 'age': 25}
new_data = {'city': 'New York', 'gender': 'Male'}
my_dict |= new_data
print(my_dict)
|
Output :
{'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
15 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...