• Python Basics

  • Python Variables

  • Operators in Python

  • Conditional Statements in Python

  • Python Lists

  • Python Tuples

  • Python Sets

  • Python Dictionaries

  • Loops in Python

  • Python Arrays and Functions

  • Conclusion

Python Update Dictionary

Update Dictionary Items in Python

In Python, dictionaries are data structures that allow you to store data in key-value pairs. One of the key features of dictionaries is their mutability, which means you can change, add, or remove items as needed. In this lesson, we will explore how to change existing values in a dictionary and update the dictionary using the update() method.

1. Changing Values in a Dictionary

To modify the value of a specific item in a dictionary, you simply reference the key associated with that value and assign a new value to it.

Example: Change a Value Using Key Name

python
1# Creating a dictionary to store car details
2car_details = {
3    "brand": "Honda",
4    "model": "Civic",
5    "year": 2021
6}
7
8# Changing the "year" of the car to 2022
9car_details["year"] = 2022
10
11print(car_details)  # Output: {'brand': 'Honda', 'model': 'Civic', 'year': 2022}

In this example, the value associated with the key "year" is updated to reflect the new year of the car.

2. Updating a Dictionary with the

The update() method provides a convenient way to update multiple items in a dictionary at once. You can pass a dictionary or any iterable object with key-value pairs as an argument.

Example: Update Dictionary Values

python
1# Creating a dictionary with vehicle information
2vehicle_info = {
3    "brand": "Toyota",
4    "model": "Corolla",
5    "year": 2020
6}
7
8# Updating the "model" and "year" of the vehicle
9vehicle_info.update({"model": "Camry", "year": 2021})
10
11print(vehicle_info)  # Output: {'brand': 'Toyota', 'model': 'Camry', 'year': 2021}

In this example, both the "model" and "year" keys are updated simultaneously using the update() method.

3. Updating with an Iterable Object

You can also use the update() method with an iterable object, such as a list of tuples or a list of lists, where each sublist contains a key-value pair.

Example: Update Using a List of Tuples

python
1# Creating a dictionary for student grades
2student_grades = {
3    "Alice": 85,
4    "Bob": 78,
5    "Charlie": 92
6}
7
8# Updating grades using a list of tuples
9grade_updates = [("Alice", 90), ("Bob", 82)]
10
11# Updating the dictionary with new grades
12for student, grade in grade_updates:
13    student_grades.update({student: grade})
14
15print(student_grades)  # Output: {'Alice': 90, 'Bob': 82, 'Charlie': 92}

Here, we iterate through the list of tuples, using update() to change the grades of the specified students.

Frequently Asked Questions