Introduction

A dictionary in Python is a collection of items that store data as key-value pairs. We can access and manipulate dictionary items based on their key. Dictionaries are mutable and allow us to add new items to them.

The quickest way to add a single item to a dictionary is by using referencing a dictionary’s index with a new key and assigning a value. For example, we add a new key-value pair like this:

snacks['chocolate'] = 5

Python allows adding multiple items to dictionaries as well. In this tutorial, we’ll take a look at how to add keys to a dictionary in Python.

Add Key to a Python Dictionary

There are multiple ways to add a new key-value pair to an existing dictionary. Let’s have a look at few common ways to do so.

Add Key with Value

We can add a new key to a dictionary by assigning a value to it. If the key is already present, it overwrites the value it points to. The key has to be written in subscript notation to the dictionary like this:

my_dictionary[new_key] = new_value

This key-value pair will be added to the dictionary. If you’re using Python 3.6 or later, it will be added as the last item of the dictionary.

Let’s make a dictionary, and then add a new key-value pair with this approach:

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

This will result in:

{1: 1, 2: 4, 3: 9, 4: 16}

#python #data structures

Python: How to Add Keys to Dictionary
3.10 GEEK