Python | Add new keys to a dictionary

05 Jul, 2022
In this article, we will cover how to add a new Key to a Dictionary in Python. We will use 7 different methods to append new keys to a dictionary.
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. Each key-value pair in a Dictionary is separated by a colon: 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. Let’s see how can we add new keys to a dictionary using different ways to a dictionary.
Python3
# Let's create a dictionary, the functional way # Create your dictionary classclass my_dictionary(dict):     # __init__ function    def __init__(self):        self = dict()     # Function to add key:value    def add(self, key, value):        self[key] = value  # Main Functiondict_obj = my_dictionary() dict_obj.add(1, 'Geeks')dict_obj.add(2, 'forGeeks') print(dict_obj)
Output:
{1: 'Geeks', 2: 'forGeeks'}
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 will point to that value. If the key exists, the current value it points to will be overwritten. 
Python3
dict = {'key1': 'geeks', 'key2': 'fill_me'}print(& quot       Current Dict is: & quot       , dict) # using the subscript notation# Dictionary_Name[New_Key_Name] = New_Key_Valuedict['key2'] = 'for'dict['key3'] = 'geeks'print(& quot       Updated Dict is: & quot       , dict)
Output:
Current Dict is:  {'key1': 'geeks', 'key2': 'fill_me'}
Updated Dict is:  {'key3': 'geeks', 'key1': 'geeks', 'key2': 'for'}
When we have to update/add a lot of key/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(& quot       Current Dict is: & quot       , dict) # adding key3dict.update({'key3': 'geeks'})print(& quot       Updated Dict is: & quot       , dict) # adding dict1 (key4 and key5) to dictdict1 = {'key4': 'is', 'key5': 'fabulous'}dict.update(dict1)print(dict) # by assigningdict.update(newkey1='portal')print(dict)
Output:
Current Dict is:  {'key2': 'for', 'key1': 'geeks'}
Updated Dict is:  {'key2': 'for', 'key3': 'geeks', 'key1': 'geeks'}

{'key4': 'is', 'key2': 'for', 'key5': 'fabulous', 'key3': 'geeks', 'key1': 'geeks'}

{'key3': 'geeks', 'newkey1': 'portal', 'key1': 'geeks',
        'key4': 'is', 'key2': 'for', 'key5': 'fabulous'}
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'} # using __setitem__ methoddict.__setitem__('newkey2', 'GEEK')print(dict)
Output:
{'key2': 'for', 'newkey2': 'GEEK', 'key1': 'geeks'}
We can merge the old dictionary and 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} # will create a new dictionarynew_dict = {**dict, **{'c': 3}} print(dict)print(new_dict)
Output:
{'b': 2, 'a': 1}
{'b': 2, 'c': 3, 'a': 1}
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'}
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"] # Using for loop enumerate()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'}
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] = valueprint(dictionary)
Output:
{'key2': 'geeks', 'key1': 'for', 'key3': 'geeks'}
surajkumarguptaintern
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python