Append to a Python dictionary using a for loop

This tutorial will discuss how to append to a Python dictionary using a for loop.

Suppose we have a dictionary and we want to add items to this dictionary in a for loop.

# Student data dictionary with names as keys and ages as values
student_data = {
    "Varun Sharma": 21,
    "Renuka Singh": 19,
    "Sachin Roy": 20
}

The new items we want to add are in a list of tuples.

# List of additional student data to append
new_items = [
    ("John Smith", 18),
    ("Sara Johnson", 22),
    ("Alex Williams", 20)
]

To add all the items in this list into the dictionary, we iterate over all the items in the list of tuples. For each tuple, we add a new key-value pair to the dictionary using square brackets.

# Append additional student data to the
# dictionary using a for loop
for name, age in new_items:
    student_data[name] = age

This is how we can add or append to a dictionary using a for loop in Python.

Let’s see the complete example,

# Student data dictionary with names as keys and ages as values
student_data = {
    "Varun Sharma": 21,
    "Renuka Singh": 19,
    "Sachin Roy": 20
}

# List of additional student data to append
new_items = [
    ("John Smith", 18),
    ("Sara Johnson", 22),
    ("Alex Williams", 20)
]

# Append additional student data to the
# dictionary using a for loop
for name, age in new_items:
    student_data[name] = age

# Print the updated student data dictionary
print(student_data)

Output

{'Varun Sharma': 21, 'Renuka Singh': 19, 'Sachin Roy': 20, 'John Smith': 18, 'Sara Johnson': 22, 'Alex Williams': 20}

Summary

Today, we learned how to append to a Python dictionary using a for loop.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top