Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair. While using Dictionary, sometimes, we need to add or modify the key/value inside the dictionary. Let’s see how to add a key:value pair to dictionary in Python.
Code #1: Using Subscript notation This method will create a new key:value pair on a dictionary by assigning a value to that key.
Python3
dict = {'key1':'geeks', 'key2':'for'}
print("Current Dict is: ", dict)
dict['key3'] = 'Geeks'
dict['key4'] = 'is'
dict['key5'] = 'portal'
dict['key6'] = 'Computer'
print("Updated Dict is: ", dict)
|
Output:
Current Dict is: {‘key2’: ‘for’, ‘key1’: ‘geeks’} Updated Dict is: {‘key3’: ‘Geeks’, ‘key5’: ‘portal’, ‘key6’: ‘Computer’, ‘key4’: ‘is’, ‘key1’: ‘geeks’, ‘key2’: ‘for’}
Time Complexity: O(1)
Auxiliary Space: O(1)
Code #2: Using update() method
Python3
dict = {'key1':'geeks', 'key2':'for'}
print("Current Dict is: ", dict)
dict1 = {'key3':'geeks', 'key4':'is', 'key5':'fabulous'}
dict.update(dict1)
dict.update(newkey1 ='portal')
print(dict)
|
Output:
Current Dict is: {‘key2’: ‘for’, ‘key1’: ‘geeks’} {‘newkey1’: ‘portal’, ‘key4’: ‘is’, ‘key2’: ‘for’, ‘key1’: ‘geeks’, ‘key5’: ‘fabulous’, ‘key3’: ‘geeks’}
Time Complexity: O(1)
Auxiliary Space: O(1)
Code #3: Taking Key:value as input
Python3
class my_dictionary(dict):
def __init__(self):
self = dict()
def add(self, key, value):
self[key] = value
dict_obj = my_dictionary()
dict_obj.key = input("Enter the key: ")
dict_obj.value = input("Enter the value: ")
dict_obj.add(dict_obj.key, dict_obj.value)
dict_obj.add(2, 'forGeeks')
print(dict_obj)
|
Output:
{'1': 'Geeks', 2: 'forGeeks'}
Time Complexity: O(1)
Auxiliary Space: O(n)
Code #4: Using a dictionary comprehension
For example, you can create a new dictionary that adds a key:value pair to an existing dictionary like this:
Python3
existing_dict = {'key1': 'value1', 'key2': 'value2'}
new_key = 'key3'
new_value = 'value3'
updated_dict = {**existing_dict, new_key: new_value}
print(updated_dict)
|
Output
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
This creates a new dictionary called updated_dict that contains all the key:value pairs from existing_dict, as well as the new key:value pair ‘key3’: ‘value3’.
Time Complexity: O(n)
Auxiliary Space: O(n)
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 :
24 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...