×

Adding a key-value pair to dictionary in Python

Python dictionaries are collections of unsorted key-value pairs. This article will examine a method for adding new key-value teams to an existing dictionary.

Dictionary in Python

With the aid of curly brackets and commas, Python enables you to build dictionaries from lists of entries. Dictionary key-value pairs are saved in pairs, with the critical element being the other. Values in dictionaries can be any data and duplicated, unlike keys, which cannot be repeated and need to be immutable.

The structure is wrapped in curly brackets, commas separate the elements, and colons separate each key and value (:). A dictionary without any words can be written as follows:

In Python, a dictionary is a group of objects that stores data as key-value pairs. The dictionary items can be accessed and changed based on their key. Dictionaries can be changed and have new words added to them.

By giving a value to a new key that makes reference to the dictionary's index, a single item can be added to a dictionary the shortest possible method. As an illustration, let's add a fresh key-value combination like this:

Cars['Audi'] = 1

Multiple entries can be added to dictionaries using Python.

Add a Key to a Python dictionary

A key-value pair can be added in several ways to an existing dictionary.

Include Key and Value

A dictionary's additional keys can be added by giving them a value. The value the key points to is overwritten if it already exists. The key must be presented using the dictionary's subscript notation as follows:

my_dictionary[new_key] = new_value

The dictionary will add this key-value pair. If Python 3.6 or later is used, it will be included as the dictionary's final entry.

Let's create a dictionary and then use the following method to add a new key-value pair:

Example

squares = {2: 2,8: 1, 6: 4}
squares[6] = 16 # Adding new key-value pair
print(squares)

Output

Adding a key-value pair to dictionary in Python

Dictionary Without Value-Add Key

With any techniques described, the user can substitute None for the value if you only want to add a key.

Example

squares = {2: 2,8: 1, 6: 4}
squares['x'] = None # Adding new key-value pair
print(squares)

Output

Adding a key-value pair to dictionary in Python

Add several Key-Value Pairs together with an update ()

Multiple key-value pairs can be added to an existing dictionary in Python. The update () method is used to accomplish this. This method adds new key-value teams to the dictionary using an argument of type dict or any iterable having a length of two, such as ((key1, value1),).

The new value replaces the key if it already exists in the dictionary.

Dictionary.update(new key=new value) is one way to give the keys and their matching values to this method as keyword arguments.

Adding additional keys and values to a dictionary is likely the most common practice.

Let's add many key-value pairs to a dictionary using the update () method:

Example

rainbow = {'violet' : 1}


# Update by passing the dictionary
new_key_values_dict = {'red': 2, 'green': 3}
rainbow.update(new_key_values_dict)
print("update by passing dictionary")
print(rainbow)


# Update by passing iterables
new_key_values_itr = (('yellow, 4'), ('indigo', 5))
rainbow.update(new_key_values_itr)
print("update by passing iterables")
print(rainbow)


# updating through iterable passing
rainbow.update(orange=6, Blue=7)
print("update using keyword arguments")
print(rainbow)

Output

Adding a key-value pair to dictionary in Python

Merge Operator (Python 3.9+) usage

The built-in dict class now supports the merge (|) and update (|=) operators of Python version 3.9.

These are efficient techniques for adding several key-value pairs to a dictionary. The keys and values of both specified dictionaries are combined into a new dictionary via the merge (|) operator. Then, we may add this finding to a new dictionary.

The second dictionary's key-value pairs are added to the first dictionary via the update (|=) operator, though. As a result, some key-value teams from another dictionary are added to the existing vocabulary.

Conclusion

Using subscript notation, we first created the key-value pair by giving each key in the dictionary a value. The update () method for adding multiple key-value teams to a dictionary was then examined. The Update () method has also been used with the types dictionary, tuple, and keyword arguments. Finally, we investigated the Merge and Update operators introduced in Python 3.9 and beyond.

The most common mechanism for adding new keys to an existing dictionary is the dictionary's update() method.


Related Topics

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Python Set symmetric_difference_update() method

Python Set symmetric_difference_update() method The set.symmetric_difference_update() method in Python updates the original set by removing items that are present in both sets and inserting the other items of the set. Syntax set.symmetric_difference_update(set1) Parameter set- This parameter represents the first...

2 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python String isspace() method

Python String isspace() method The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given...

2 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Array to String in Python

What is an Array: The idea behind an array is to group several items of the same type, making it easier to locate each element by adding an extra offset to...

4 minutes read.

Python Break Statement

In Python, loops are used to automate and repeat processes in an effective manner. However, there may be occasions when you wish to entirely exit the loop, skip an iteration,...

2 minutes read.

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally...

6 minutes read.

GUI Calculator in Python

Introduction In Python, we can develop a GUI(Graphical User Interface) with multiple options. It offers us some great and commonly used methods for the development of the Graphical User Interface. Tkinter...

4 minutes read.

Python String title() method

Python String title() method The string.title() method in Python returns a string where the first character in every word is upper case. If the word contains a number or a symbol,...

1 minute read.

How to Install Scikit-Learn

Sklearn or Scikit-learn is a python library used for machine learning. It contains many features like classification, regression, clustering, and Dimensionality reduction algorithms. Sklearn is used to build machine learning...

3 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Hog Descriptor Opencv Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.

Python Dictionary clear() method

Python Dictionary clear() method The dictionary.clear() method in Python removes all the elements from a dictionary. Syntax dictionary.clear() Parameter NA Return None Example 1 # Python program explaining # the dictionary.clear() method # initialising the dictionary fruits =...

1 minute read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python zip() Function

Python zip() Function The zip() function makes an iterator that aggregates elements from each of the iterables and returns an iterator of tuples. Syntax zip(*iterables) Parameter iterables: Iterator objects that will be joined together Return This function...

1 minute read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.