Open In App

Add new keys to a dictionary in Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore various methods to add new keys to a dictionary in Python. Let’s explore them with examples:

Using Assignment Operator (=)

The simplest way to add a new key is by using assignment operator (=).

Python
d = {"a": 1, "b": 2}

d["c"] = 3

print(d)

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation: d[“c”]: creates a new key “c” and its value is assigned as “3“. If key “c” already exists then it will replace the existing value with new value.

Using update()

The update() method can be use to merge dictionaries or add multiple keys and their values in one operation.

Python
d = {"a": 1, "b": 2}

# Adding a single key-value pair
d.update({"c": 3})

# Adding multiple key-value pairs
d.update({"d": 4, "e": 5})

print(d)

Output
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Explanation:

  • update() accepts another dictionary as an argument and adds its key-value pairs.
  • If a key already exists then its value is updated.

Using | Operator (Python 3.9+)

We can use | operator to create a new dictionary by merging existing dictionaries or adding new keys and values. This method does not modify the original dictionaries but returns a new dictionary with updated data.

Python
d = {"a": 1, "b": 2}

res = d | {"c" : 3}

print(res)

Output
{'a': 1, 'b': 2, 'c': 3}

Explanation:

  • d | {“c”: 3} creates a new dictionary by merging d with another dictionary containing key “c”.
  • original dictionary d remains unchanged.
  • if keys overlap, values from the right-hand operand overwrite those on the left.

Note: If there are duplicate keys then value from the right hand dictionary overwrites the value from the left hand dictionary.

Related Articles:


Next Article

Similar Reads

  翻译: