Open In App

Python - Add Items to Dictionary

Last Updated : 30 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary and our task is to add a new key-value pair to it. For example, if we have the dictionary d = {"a": 1, "b": 2} and we add the key "c" with the value 3, the output will be {'a': 1, 'b': 2, 'c': 3}. This can be done using different methods like direct assignment, update(), or setdefault(). Let’s explore the most efficient ways to achieve this.

Using Direct Assignment

We can directly assign a new key-value pair to the dictionary using the assignment operator.

Python
a = {"name": "Olivia", "age": 25}

# Add an item to the dictionary
a["city"] = "New York"

print(a)

Output
{'name': 'Olivia', 'age': 25, 'city': 'New York'}

Explanation:

  • A new key-value pair is added to the dictionary using the syntax dictionary[key] = value.
  • If the key already exists, the value is updated otherwise, a new entry is created.

Let's explore some more methods and see how we can add items to dictionary.

Using update()

update() method allows us to add multiple key-value pairs to the dictionary.

Python
a = {"name": "Olivia", "age": 25}

# Add multiple items to the dictionary
a.update({"city": "New York", "country": "USA"})

print(a)

Output
{'name': 'Olivia', 'age': 25, 'city': 'New York', 'country': 'USA'}

Explanation:

  • update() method takes another dictionary or an iterable of key-value pairs as input.
  • It adds the new items to the dictionary or updates the values of existing keys.

Using setdefault()

setdefault() method adds an item to the dictionary only if the key does not already exist.

Python
a = {"name": "Olivia", "age": 25}

# Add an item only if the key does not exist
a.setdefault("city", "New York")

print(a)

Output
{'name': 'Olivia', 'age': 25, 'city': 'New York'}

Explanation:

  • setdefault() method checks if the key exists in the dictionary.
  • If the key is not found, it adds the key with the specified value.
  • If the key exists, the method returns the existing value without making any changes.

Using for Loop for Bulk Additions

For more complex scenarios, we can use a for loop to add items to the dictionary dynamically.

Python
a = {"name": "Olivia", "age": 25}

# Data to add
b = [("city", "New York"), ("country", "USA")]

# Add items using a loop
for k, v in b:
    a[k] = v

print(a)

Output
{'name': 'Olivia', 'age': 25, 'city': 'New York', 'country': 'USA'}

Explanation:

  • for loop iterates over the list of key-value pairs and adds them to the dictionary using direct assignment.
  • This approach is flexible when the data to be added is stored in another iterable.

Next Article

Similar Reads