How to add a new key-value pair item to a dictionary in Python

Published on Aug. 22, 2023, 12:15 p.m.

To add a new key-value pair item to a dictionary in Python, you can use either of the following methods:

  1. Dictionary indexing:
my_dict = {'apple': 1, 'banana': 2}
my_dict['orange'] = 3

This will add the key-value pair ('orange', 3) to the dictionary my_dict.
2. The dict.update() method:

my_dict = {'apple': 1, 'banana': 2}
my_dict.update({'orange': 3})

This will update the dictionary my_dict with the key-value pair ('orange', 3).

Here’s an example of adding a new item to a dictionary using Dictionary indexing:

# Creating a dictionary
fruit_counts = {"apples": 5, "oranges": 8, "bananas": 12}

# Adding a new item to the dictionary
fruit_counts["pears"] = 6
print(fruit_counts)

This will output:

{"apples": 5, "oranges": 8, "bananas": 12, "pears": 6}

Note that if the key already exists in the dictionary, these methods will update the existing value associated with that key rather than adding a new key-value pair.

Tags: