Open In App

Python | Add new keys to a dictionary

Last Updated : 18 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Before learning how to add items to a dictionary, let’s understand in brief what a  dictionary is. 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.

How to Add Keys and Values to a Dictionary

To add a new item in the dictionary, you need to add a new key and insert a new value respective to it. There are various methods to add items to a dictionary in Python here we explain some generally used methods to add to a dictionary in Python. 

  1. Using Subscript notation 
  2. Using update() Method
  3. Using __setitem__ Method
  4. Using the  ** operator 
  5. Using If statements
  6. Using enumerate() Method
  7. Using Zip
  8. Using a Custom Class
  9. Using Merge | Operator

Add to a Python Dictionary 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)
 
# using the subscript notation
# Dictionary_Name[New_Key_Name] = New_Key_Value
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 Python Dictionary 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)
 
# adding key3
dict.update({'key3': 'geeks'})
print("Updated Dict is:", dict)
 
# adding dict1 (key4 and key5) to dict
dict1 = {'key4': 'is', 'key5': 'fabulous'}
dict.update(dict1)
print("After adding dict1 is:" , dict)
 
# by assigning
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 Python Dictionary using the __setitem__ Method

The __setitem__ method is used to add a key-value pair to a dictionary. It should be avoided because of its poor performance (computationally inefficient).

Python3




dict = {'key1': 'geeks', 'key2': 'for'}
 
# using __setitem__ method
dict.__setitem__('newkey2', 'GEEK')
print(dict)


Output :

{'key1': 'geeks', 'key2': 'for', 'newkey2': 'GEEK'}

Add to Python Dictionary 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}
 
# will create a new dictionary
new_dict = {**dict, **{'c': 3}}
 
print(dict)
print(new_dict)


Output :

{'a': 1, 'b': 2}
{'a': 1, 'b': 2, 'c': 3}

Add to Python 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 Python Dictionary using enumerate() Method

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'}

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 Python Dictionary with a Custom Class

At first, we have to learn how we create dictionaries in 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




# Create your dictionary class
class my_dictionary(dict):
 
  # __init__ function
  def __init__(self):
    self = dict()
 
  # Function to add key:value
  def add(self, key, value):
    self[key] = value
 
 
# Main Function
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




# Existing dictionary
my_dict = {'name': 'John', 'age': 25}
 
# New key-value pairs to add
new_data = {'city': 'New York', 'gender': 'Male'}
 
# Adding new keys using the merge operator
my_dict |= new_data
 
# Display the updated dictionary
print(my_dict)


Output :

{'name': 'John', 'age': 25, 'city': 'New York', 'gender': 'Male'}

In this tutorial, we have covered multiple ways to add items to a Python dictionary. We have discussed easy ways like the update() method and complex ways like creating your own class. Depending on whether you are a beginner or an advanced programmer, you can choose from a wide variety of techniques to add to a dictionary in Python. 

You can read more informative articles on how to add to a dictionary:



Previous Article
Next Article

Similar Reads

Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python | Add keys to nested dictionary
Addition of keys in dictionaries have been discussed many times, but sometimes, we might have a problem in which we require to alter/add keys in the nested dictionary. This type of problem is common in today's world with advent of NoSQL databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using for loop Step-by-step
5 min read
Add a new column in Pandas Data Frame Using a Dictionary
Pandas is basically the library in Python used for Data Analysis and Manipulation. To add a new Column in the data frame we have a variety of methods. But here in this post, we are discussing adding a new column by using the dictionary. Let's take Example! # Python program to illustrate # Add a new column in Pandas # Importing the pandas Library im
2 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
three90RightbarBannerImg