How to update Python dictionary values

In this tutorial, we will learn about How to update Python dictionary values. In Python, you can update the values of a dictionary in two ways: by using the update() method or by using square brackets.

A dictionary in Python represents a collection of key-value pairs, enclosed in curly braces. The keys are unique and separated from their corresponding values by a colon, while items are separated by commas. The keys are located on the left side of the colon, and their corresponding values are on the right side.

Let’s start by creating a Python dictionary and retrieving all the values. In this example, we have included four key-value pairs in the dictionary and displayed them. The keys in the dictionary are “Product,” “Model,” “Units,” and “Available.” All keys except “Units” have string values.

By employing the update() method or using square brackets, you can easily modify the values of a dictionary.

How to update Python dictionary values

Update Python dictionary values using the dictionary update method

The update() function in Python allows us to update a dictionary by incorporating elements from another dictionary or an iterable object containing key/value pairs. This function actively modifies the dictionary, merging it with the provided elements. In the following discussion, we will explore the inner workings of this function through illustrative examples.

Syntax

dictionary_name.update(other_dictionary)

Parameters

other_dictionary or iterable: update() function takes another dictionary or an iterable containing the key-value pairs as the parameter.

Return value

The update() function doesn’t return any values

Example:

# Creating an initial dictionary
student_scores = {'Rachit': 85, 'Kunal': 92, 'Mukul': 78}

# Displaying the initial dictionary
print("Initial dictionary:")
print(student_scores)

# Updating the dictionary using update() method
new_scores = {'Kunal': 95, 'Mukul': 82, 'Sushil': 90}
student_scores.update(new_scores)

# Displaying the updated dictionary
print("\nUpdated dictionary:")
print(student_scores)


Output

Initial dictionary:
{'Rachit': 85, 'Kunal': 92, 'Mukul': 78}

Updated dictionary:
{'Rachit': 85, 'Kunal': 95, 'Mukul': 82, 'Sushil': 90}

This program demonstrates how to update the values of a Python dictionary using the update() method.

Initially, we create a dictionary called student_scores with three key/value pairs representing the scores of three students. We then print the initial dictionary.

Next, we define a new dictionary called new_scores with additional scores for some students, including updates for ‘Alice’ and ‘Michael’, as well as a new entry for ‘Jessica’.

We update the student_scores dictionary by using the update() method and passing the new_scores dictionary as an argument. This merges the new scores into the original dictionary, updating the values for ‘Alice’ and ‘Michael’, and adding the entry for ‘Jessica’.

Finally, we print the updated dictionary to see the changes.

Example: update() when tuple is passed

def update_dict_values(dictionary, key_value_tuples):
    temp_dict = dict(key_value_tuples)
    dictionary.update(temp_dict)

# Creating an initial dictionary
student_scores = {'Alice': 85, 'Bob': 90, 'Charlie': 80}

# Displaying the initial dictionary
print("Initial Dictionary:")
print(student_scores)

# Creating a tuple containing new key/value pairs
new_scores = (('Bob', 95), ('Charlie', 88), ('David', 92))

# Updating the dictionary values using update() and passing the tuple
update_dict_values(student_scores, new_scores)

# Displaying the updated dictionary
print("\nUpdated Dictionary:")
print(student_scores)


Output

Initial Dictionary:
{'Alice': 85, 'Bob': 90, 'Charlie': 80}

Updated Dictionary:
{'Alice': 85, 'Bob': 95, 'Charlie': 88, 'David': 92}

In this program, we define the update_dict_values() function, which takes a dictionary and a list of key/value tuples as arguments. Inside the function, we convert the list of tuples into a temporary dictionary using the dict() function. Then, we use the update() method to update the original dictionary with the values from the temporary dictionary.

To demonstrate the usage, we start by creating an initial dictionary called student_scores, which stores the scores of three students. We then display the initial dictionary.

Next, we create a tuple called new_scores, which contains new key/value pairs for updating the dictionary. In this case, we have new scores for ‘Bob’, ‘Charlie’, and a new student ‘David’.

Finally, we call the update_dict_values() function, passing the student_scores dictionary and the new_scores tuple as arguments. The function updates the values of the dictionary using the update() method.

After the update, we display the updated dictionary. You will see that the scores for ‘Bob’ and ‘Charlie’ have been updated, and the new student ‘David’ with his score has been added.

Example: Python Dictionary Update Value if the Key Exists

# Creating a sample dictionary
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

# Displaying the original dictionary
print("Original Dictionary:")
print(my_dict)

# Updating dictionary values if the key exists
def update_dictionary(dictionary, key, new_value):
    if key in dictionary:
        dictionary[key] = new_value

# Updating the 'age' key's value
update_dictionary(my_dict, 'age', 30)

# Updating the 'city' key's value
update_dictionary(my_dict, 'city', 'San Francisco')

# Displaying the updated dictionary
print("\nUpdated Dictionary:")
print(my_dict)


Output

Original Dictionary:
{'name': 'John', 'age': 25, 'city': 'New York'}

Updated Dictionary:
{'name': 'John', 'age': 30, 'city': 'San Francisco'}

This program showcases a function named update_dictionary() that takes a dictionary, a key, and a new value as parameters. Inside the function, it checks if the given key exists in the dictionary using the in keyword. If the key is present, it updates the corresponding value with the new value.

The program creates a sample dictionary called my_dict with initial key-value pairs. It then displays the original dictionary. The update_dictionary() function is called twice to update the values of the ‘age’ and ‘city’ keys. Finally, the updated dictionary is printed to show the changes.

This program demonstrates a practical approach to updating dictionary values if the key already exists, allowing you to easily modify specific values within a dictionary.

Update Python dictionary values by initializing

# Create a dictionary
student_scores = {'John': 85, 'Alice': 92, 'Bob': 78}

# Display the original dictionary
print("Original Scores:", student_scores)

# Update John's score using square brackets
student_scores['John'] = 90

# Display the updated dictionary
print("Updated Scores:", student_scores)


Output

Original Scores: {'John': 85, 'Alice': 92, 'Bob': 78}
Updated Scores: {'John': 90, 'Alice': 92, 'Bob': 78}

In the above program, we first create a dictionary student_scores with the names of students as keys and their respective scores as values. We then print the original dictionary.

To update a specific value in the dictionary, we use square brackets and provide the key of the element we want to update. In this case, we update John’s score from 85 to 90.

Finally, we print the updated dictionary, showcasing the change in John’s score.

By using square brackets, we can easily access and update individual values within a dictionary in Python.

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!