Python Add To Dictionary – [9 ways]

Python Dictionary is used to store the data in the key-value pair.

In python, you can add keys to the dictionary using the update() method or using the subscript notation [ ] and equal to operator.

Dictionaries are

  • Changeable
  • Ordered
  • Doesn’t allow duplicate keys
  • Keys must be of type of immutable objects such as String or int or a tuple

However, different keys can have the same value.

.. If an existing key is added to a dictionary, then it’ll replace the existing key-value pair rather than creating a new entry.

Keys and values are separated using the : operator and each key-value pair is separated using , in the dictionary.

In this tutorial, you’ll learn the different methods available to add keys to the dictionary.

If You’re in Hurry…

Here is an example of how to add keys to a dictionary in python.

# Assigning Key values pair directly. 

mydict = {"existingkey": "value"}

print(mydict)


#Assigning value to a specific key. This key will be added if its not available already. 

mydict["newlyAddedkey"] = "newlyAddedValue"

print(mydict)

Output

{'existingkey': 'value'}

{'existingkey': 'value', 'newlyAddedkey': 'newlyAddedValue'}

If You Want to Understand Details, Read on…

There are different methods available to add a new items to the dictionary in python. They are explained below.

Using Subscript Notation ( [ ] Operator)

In this section, you’ll learn how to add new key-value pairs to dictionary objects using the Subscript notation.

Subscript notation is defined as square brackets [] and it’s used to access the elements of the list or set or a dictionary.

Together with [] and = operator, you can also assign a key-value pair to existing dictionary object.

The below snippet shows how to add a new key to a dictionary object

Example

mydict = {"existingkey": "value"}

print(mydict)

mydict["newlyAddedkey"] = "newlyAddedValue"

print(mydict)

Output

{'existingkey': 'value'}

{'existingkey': 'value', 'newlyAddedkey': 'newlyAddedValue'}

This is also known as appending a new key value to the dictionary.

Using Update() method

In this section, you’ll learn how to add new key-value to existing dict using the update() method.

Syntax

It accepts a mandatory mapping parameter which is also another dictionary consisting of one or more key-value pairs.

Example

The below example shows how new keys and values can be added to a dictionary using the update() method.

mydict = {"existingkey": "value"}

new_dict = {"NewKey": "NewValue"}

mydict.update(new_dict)

print(mydict)

Output

{'existingkey': 'value', 'NewKey': 'NewValue'}

This is how to add elements to a dictionary using the update() method.

Using __setitem()__ method

In this section, you’ll learn how to add new keys to the dictionary using the setitem() method in Python.

It is not recommended to use this method considering performance complexity.

Syntax

setItem() accepts key and value as parameters and sets the value into the calling object.

Example

The below example shows how to add a new key to a dictionary using setitem() method.

mydict = {"existingkey": "value"}

# using __setitem__ method
mydict.__setitem__("newkey2", "Vidhya")

print(mydict)

Output

{'existingkey': 'value', 'newkey2': 'Vidhya'}

This is how to add elements to the dictionary using the __setitem__() method.

Using ** operator

In this section, You’ll add new Key-value Using ** operator.

This operator denotes dictionary unpacking. This operator’s operand must be a mapping.

Each mapping item is added to the new dictionary.

Using ** in front of key-value pairs like **{"five": "5"} will unpack it as a new dictionary object.

The below example shows how the ** object unpacks two dictionary objects and adds them to a new dictionary object.

Example

mydict = {
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
}

# Using ** will create a new dictionary
my_new_dict = {**mydict, **{"five": "5"}}

print(mydict)

print("\nNew Dictionary with new key value pair added:")

print(my_new_dict)

Output

{'one': '1', 'two': '2', 'three': '3', 'four': '4'}

New Dictionary with new key value pair added:
{'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5'}

This is how you can use the ** operator. Next, you’ll learn Merge operator to add an element.

Using Merge Operator

In this section, you’ll learn how to add new keys to the Python dictionary using the Python merge operator.

This merge operator is available since python version 3.9.

You can check the Python version in cmd using the below command.

import sys

print(sys.version)

Output

3.9.2 (default, Sep  4 2020, 00:03:40) [MSC v.1916 32 bit (Intel)]

If your version is equal to or greater than 3.9, then you can use this merge to add elements to the dictionary. Else, you cannot use it.

There are two types of the merge operations.

First Method using Merge

Two dictionaries will be merged and a new dictionary will be created when you use | operator between two dictionaries.

Example

num1 = {"one": 1, "two": 2, "three": 3}

num2 = {"four": 4, "five": 5, "six": 6}

# Merge operator
numbers = num1 | num2

print("Created new Dictionary using merge : ", numbers)

Output

Created new Dictionary using merge : {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six':'6'}

Second Method using Merge

The items from the second dictionary will be merged into the first dictionary rather than creating a new dictionary object when you use |= operator between two dictionaries.

Example

# Update operator, keys from the second dictionary added to first.
num1 |= num2

print("using update:", num1)

Output

using update: {'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six':'6'}

This is how you can add new key-value pair to dictionary objects in python using the two different Merge operations while using the Python version greater than 3.9.

Add new key value pair to dictionary without overwriting

In this section, you’ll learn how to add new key-value pairs to the dictionary without overwriting the existing key-value pairs.

This can be done by checking if the key already exists in the dictionary using the in operator and the IF statements.

Example

Before adding a new key to the dictionary, statement if "one" not in mydict: is used to check if the key doesn’t exist in the dictionary.

If this statement is evaluated to true, then the key will be added to the dictionary. If evaluated to false, an error message will be printed.

mydict = {"one": 1, "two": 2, "three": 3}

if "one" not in mydict:
    mydict["one"] = "11"
else:
    print("Dictionary already has key : One. Hence value is not overwritten ")

print(mydict)

Output

 Dictionary already has key : One. Hence value is not overwritten 
    {'one': 1, 'two': 2, 'three': 3}

In the below example, the key “four” is not available in the dictionary. Hence it’ll be added to the dictionary.

Example

if "four" not in mydict:
    mydict["four"] = "4"
    print("\nAdded new key value pair to dictionary without overwriting")

print(mydict)

Output

Added new key value pair to dictionary without overwriting
{'one': 1, 'two': 2, 'three': 3, 'four': '4'}

This is how to add a new key to dict, if the key doesn’t exist in dictionary.

Add new key value pair to nested dictionary

In this section, you’ll learn how to add a new key-value pair to a nested dictionary.

A nested Dictionary is a dictionary that contains a dictionary object for each key in the dictionary.

Example

In the below example, for NewKey the value is added as {'subkey1': 'value1'} which is a dictionary by itself making the mydictionary as a nested dictionary.

mydict = {
    "one": "1",
    "two": "2",
    "three": "3",
    "four": "4",
}

mydictionary = dict.fromkeys(mydict, {})

mydictionary["NewKey"] = {"subkey1": "value1"}

print(mydictionary)

Output

{'one': {}, 'two': {}, 'three': {}, 'four': {}, 'NewKey': {'subkey1': 'value1'}}

Add new key value pair to dictionary from list using for loop

In this section, you’ll learn how to add new key-value pair to the dictionary using for loop from the list of values.

First, create a list of items.

Then Iterate the list using the enumerate() function and add each list item into the dictionary using its index as a key for each value.

Example

mylist = ["one", "two", "three"]

# Using for loop enumerate()
for i, val in enumerate(mylist):

    mydict[i] = val

print(mydict)

You’ll see the below output of the dictionary created with the help of for loop.

Output

{0: 'one', 1: 'two', 2: 'three'}

This is how you can add new keys to the dictionary using for loop.

Add new key to dictionary without value

Until now, you’ve seen various ways to add new keys to the dictionary.

There may be a situation, where you want to add the key to the dictionary without value (Maybe when the value is not known upfront).

The value can be updated later point in time in your program.

You can add a new key to the dictionary without value using the None keyword. It’ll just add a new key to the dictionary.

Example

mydict = {
    "0": "zero",
    "1": "one",
    "2": "two"
}

mydict["keywithoutvalue"] = None

print(mydict)

You’ll see the below output, where there is a key named keywithoutvalue exists without any value.

Output

{0: 'zero', 1: 'one', 2: 'two', 'keywithoutvalue': None}

Conclusion

Python dictionaries are the most commonly used data structures to store data in your program.

You may need to add a new key to the dictionary, add key-value pair, add it using for loop or lists or add a key without a value.

In this tutorial, you’ve seen all the available ways to add keys to dictionary objects in Python.

If you have any doubts, feel free to comment below.

Leave a Comment