How to Add a Key To a Dictionary in Python – Definitive Guide

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

You can add a key to dictionary in python using mydict["newkey"] = "newValue" method.

This tutorial teaches you the different methods to add a key to a dictionary in Python

Using Subscript Notation ( [ ] Operator)

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

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

Code

The following code shows how to add a new key to a dictionary object.

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.

Code

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

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.

Code

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

mydict = {"existingkey": "value"}

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

print(mydict)

Output

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

Using ** operator

In this section, You’ll add a 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.

Code

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

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

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)]

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.

Code

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

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,

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

Add new key to dictionary without value

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}

Additional Resources

1 thought on “How to Add a Key To a Dictionary in Python – Definitive Guide”

Leave a Comment