The Wayback Machine - https://web.archive.org/web/20241003060820/https://www.geeksforgeeks.org/python-add-new-keys-to-a-dictionary/
Open In App

Python | Add new keys to a dictionary

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

Python
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.

Python
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).

Python
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.

Python
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.

Python
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.

Python
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 = {}.

Python
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.

Python
# 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.

Python
# 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:

Python | Add new keys to a dictionary – FAQs

How to Add a New Key to a Dictionary in Python

Adding a new key to a dictionary in Python is straightforward. Simply assign a value to a new key in the dictionary. If the key does not already exist, it will be added along with its value:

my_dict = {'a': 1, 'b': 2}
my_dict['c'] = 3 # Adding a new key 'c' with value 3
print(my_dict) # Output: {'a': 1, 'b': 2, 'c': 3}

How to Add New Keys and Values to an Empty Dictionary in Python

To add keys and values to an empty dictionary, you use the same approach as adding to any dictionary:

my_dict = {}
my_dict['first'] = 'Hello'
my_dict['second'] = 'World'
print(my_dict) # Output: {'first': 'Hello', 'second': 'World'}

How to Add Key Without Value in Dictionary in Python

In Python, every key in a dictionary needs to have an associated value. However, you can assign a None or some other placeholder if you need to create a key without a meaningful value:

my_dict = {}
my_dict['key'] = None # Using None as a placeholder
print(my_dict) # Output: {'key': None}

How Do I Add a New Key to a Nested Dictionary in Python?

To add a new key to a nested dictionary, you first need to access the nested dictionary and then add the key to it. Here’s how you might do it:

nested_dict = {'level1': {'level2': 42}}
nested_dict['level1']['new_key'] = 'new_value'
print(nested_dict) # Output: {'level1': {'level2': 42, 'new_key': 'new_value'}}

Ensure that the nested dictionary (level1) exists before trying to add a key to it to avoid a KeyError.

How Do I Add a Key from One Dictionary to Another in Python?

To add a key from one dictionary to another, simply assign the value from one dictionary to a key in the other dictionary:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3}
dict2['new_b'] = dict1['b'] # Copying key 'b' from dict1 to dict2 as 'new_b'
print(dict2) # Output: {'c': 3, 'new_b': 2}

This approach copies the value associated with key 'b' from dict1 to a new key 'new_b' in dict2. This method does not link the values between the dictionaries; it merely copies the value, so subsequent changes to the original dictionary do not affect the copied value



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
How to Add Duplicate Keys in Dictionary Python
In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will see how to store multiple values for a single key using two simple approaches. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique. This means that if you try to add a key that alread
3 min read
How to Add New Line in Dictionary in Python
When working with dictionaries, you might find yourself in a situation where you need to add a new key-value pair. This process is straightforward, but understanding the nuances can be very helpful. In this article, we will explore how to add new lines (key-value pairs) to dictionaries in Python with practical examples. Understanding Python Diction
3 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 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 | Check if given multiple keys exist in a dictionary
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "
3 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python - Keys associated with value list in dictionary
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in Python. Example Input: {'gfg': [4, 5], 'best': [10,
4 min read
Python - Find dictionary keys present in a Strings List
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is brute force way in
7 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Python - Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain way in which this task can be performed. Input :
5 min read
Python Dictionary keys() method
The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python. Syntax: dict.keys() Parameters: There are no parameters. Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary. Method 1
4 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
How to Add Same Key Value in Dictionary Python
Dictionaries are powerful data structures that allow us to store key-value pairs. However, one common question that arises is how to handle the addition of values when the keys are the same. In this article, we will see different methods to add values for the same dictionary key using Python. Adding the Same Key Value in PythonDictionaries in Pytho
2 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks at many ways to do this, such as comprehending di
5 min read
How to add column sum as new column in PySpark dataframe ?
In this article, we are going to see how to perform the addition of New columns in Pyspark dataframe by various methods. It means that we want to create a new column that will contain the sum of all values present in the given row. Now let's discuss the various methods how we add sum as new columns But first, let's create Dataframe for Demonstratio
4 min read
How to Add Group-Level Summary Statistic as a New Column in Pandas?
In this article, we will learn how to Add Group-Level Summary Statistic as a New Column in DataFrame Pandas. This can be done by using the concept of Statistic mean, mode, etc. This requires the following steps : Select a dataframeForm a statistical data from a column or a group of columnsStore data as a seriesAdd the series in dataframe as a colum
2 min read
Add new column with default value in PySpark dataframe
In this article, we are going to see how to add a new column with a default value in PySpark Dataframe. The three ways to add a column to PandPySpark as DataFrame with Default Value. Using pyspark.sql.DataFrame.withColumn(colName, col)Using pyspark.sql.DataFrame.select(*cols)Using pyspark.sql.SparkSession.sql(sqlQuery)Method 1: Using pyspark.sql.Da
3 min read
How to add a new column to a PySpark DataFrame ?
In this article, we will discuss how to add a new column to PySpark Dataframe. Create the first data frame for demonstration: Here, we will be creating the sample data frame which we will be used further to demonstrate the approach purpose. C/C++ Code # importing module import pyspark # importing sparksession from pyspark.sql module from pyspark.sq
8 min read
Add New Sheet to Excel Using Pandas
The article aims to implement a function in Python using Pandas to add a new sheet to an existing Excel file, facilitating efficient data organization and management within Excel workbooks. Using openpxl to add a new sheet to Excel Using PandasPandas offer a seamless interface for manipulating Excel files programmatically that allows automated and
2 min read
Add New Columns to Polars DataFrame
Polars is a fast DataFrame library implemented in Rust and designed to process large datasets efficiently. It is gaining popularity as an alternative to pandas, especially when working with large datasets or needing higher performance. One common task when working with DataFrames is adding new columns, which can be done easily in Polars. In this ar
3 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
Python | Pandas dataframe.keys()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.keys() function returns the 'info axis' for the pandas object. If the pandas object is series then it returns index. If
1 min read
Python | Pandas Series.keys()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.keys() function is an alias for index. It returns the index labels of the given
2 min read
Python IMDbPY – Info set to keys of Movie object
In this article we will see how we can convert info set to keys, we can know info sets of movie by get_movie_infoset, but even after getting the info set we are unable to use like dictionary. In order to use info set as dictionary keys we have to use infoset2keys method. Syntax : movie.infoset2keys Here movie is the imdb Movie object Action perform
2 min read
Python IMDbPY – Info set to keys of Person object
In this article we will see how we can convert info set to keys, we can know info sets of movie by get_person_infoset, but even after getting the info set we are unable to use like dictionary. In order to use info set as dictionary keys we have to use infoset2keys method. Syntax : person.infoset2keys Here movie is the imdb Person object Action perf
3 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Python - Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let's discuss the certain ways in which this task can be
7 min read
Special Keys in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Special Keys is an exclusive feature of Selenium in python, that allows pressing keys through keyboard such as ctrl+f, or shift+c+v, etc. class selenium.webdriver.common.keys.Keys handles all Keys in Selenium Python. It contains huge number of key methods one can use in Sel
1 min read
Convert ImmutableMultiDict with duplicate keys to list of lists in Python
In this article, we are going to see how to convert ImmutableMultiDict with duplicate keys to a list of lists using Python. Using Werkzeug Python Werkzeug is a WSGI utility library. WSGI is a protocol or convention that assures that your web application can communicate with the webserver and, more crucially, that web apps can collaborate effectivel
3 min read