Innovate | Connect | Transform
ContactService statusUSD $

GICT knowledge base

Learn How to Modify Python Dictionary Values Easily

Published

Python

In Python, a dictionary is a data structure that stores information in key-value pairs. Each key in a dictionary is unique and points to a specific value. You can think of it as a real-world dictionary, where each word (key) has a meaning (value).

Dictionaries are widely used because they make it easy to store, search, and update data quickly. For example, you can store user details, product prices, or student marks using keys and values. This helps you organize data neatly and access it without looping through lists.

In this guide, you’ll learn how to change dictionary items easily and correctly. You’ll see different ways to update single or multiple values, modify nested data, and avoid common mistakes.

Here’s a simple example:

student = {"name": "Ravi", "age": 20, "marks": 85}
student["marks"] = 90  # Change marks
print(student)

Output:

{'name': 'Ravi', 'age': 20, 'marks': 90}

As you can see, dictionaries let you update data instantly without creating a new one.

Understanding How Dictionaries Store Data

Key-Value Pair Concept

A Python dictionary works by storing data as key-value pairs. Each key is linked to a value, allowing you to access information quickly using the key name instead of a position or index.

For example:

person = {"name": "Asha", "age": 25, "city": "Delhi"}
print(person["city"])

Output:

Delhi

Here, “city” is the key and “Delhi” is its value. Keys must be unique, while values can be repeated.

Mutability of Dictionaries

Dictionaries are mutable, meaning you can change their contents after creation. You don’t need to make a new dictionary to update or remove data.

info = {"a": 1, "b": 2}
print(id(info))
info["b"] = 5
print(id(info))

The id() remains the same before and after modification, showing that the same dictionary object is updated in memory.

Changing Dictionary Values by Key

Direct Assignment Method

The simplest way to change a dictionary value is by using direct assignment. The syntax is straightforward:

dict_name[key] = new_value

If the key already exists, its value will be replaced with the new one. This makes it easy to update data quickly without using extra functions.

Example:

student = {"name": "Ravi", "age": 20, "marks": 85}
student["marks"] = 90
print(student)

Output:

{'name': 'Ravi', 'age': 20, 'marks': 90}

Here, the key “marks” already existed, so its value was replaced with 90.

Adding New Keys While Updating

When you assign a value to a new key that doesn’t exist in the dictionary, Python automatically adds it. This lets you update or extend your data easily.

Example:

student["grade"] = "A"
print(student)

Output:

{'name': 'Ravi', 'age': 20, 'marks': 90, 'grade': 'A'}

As you can see, the new key “grade” was added with its value “A” without any extra steps.

Updating Multiple Dictionary Items

Using the update() Method

The update() method lets you change multiple values in a dictionary at once. Its syntax is simple:

dict_name.update({key1: value1, key2: value2})

This method is useful when you want to update several items together. If a key already exists, its value will be replaced. If it doesn’t exist, a new key-value pair will be added automatically.

Example:

student = {"name": "Ravi", "age": 20, "marks": 85}
student.update({"age": 21, "grade": "A"})
print(student)

Output:

{'name': 'Ravi', 'age': 21, 'marks': 85, 'grade': 'A'}

Here, the “age” key was updated, and “grade” was added as a new entry.

Merging Two Dictionaries

You can also use update() to merge two dictionaries:

info1 = {"name": "Asha", "city": "Delhi"}
info2 = {"city": "Mumbai", "age": 25}
info1.update(info2)
print(info1)

Output:

{'name': 'Asha', 'city': 'Mumbai', 'age': 25}

When keys overlap (like “city”), values from the second dictionary replace the old ones.

In Python 3.9 and later, you can merge dictionaries even more easily using:

info1 |= info2

This works the same way as update().

Changing Nested Dictionary Items

Accessing Inner Dictionaries

A nested dictionary means a dictionary inside another dictionary. This structure is used to store grouped or detailed information, such as student records or employee details. To access or change a value inside it, you can use multiple keys in sequence.

Example:

students = {
    "Ravi": {"age": 20, "marks": 85},
    "Asha": {"age": 22, "marks": 90}
}
students["Ravi"]["marks"] = 95
print(students)

Output:

{'Ravi': {'age': 20, 'marks': 95}, 'Asha': {'age': 22, 'marks': 90}}

Here, the inner value for “marks” was updated without affecting other data.

Using Loops for Bulk Updates

You can loop through nested dictionaries to update multiple values based on conditions.

Example:

employees = {
    "E1": {"name": "Ravi", "salary": 40000},
    "E2": {"name": "Asha", "salary": 55000}
}
for emp in employees.values():
    if emp["salary"] > 50000:
        emp["salary"] += 5000
print(employees)

Output:

{'E1': {'name': 'Ravi', 'salary': 40000}, 'E2': {'name': 'Asha', 'salary': 60000}}

This code increases salaries only for employees earning more than ₹50,000, showing how to handle multiple nested updates easily.

Conditional Updates

Using Loops and If Statements

Sometimes, you may want to update only specific values based on a rule. You can do this using a simple for loop and an if statement.

Example:

data = {"a": 5, "b": 12, "c": 8}
for k, v in data.items():
    if v < 10:
        data[k] = v * 2
print(data)

Output:

{'a': 10, 'b': 12, 'c': 16}

Here, only the values less than 10 were doubled. This method is clear and easy to follow, especially for small datasets.

Using Dictionary Comprehensions

A dictionary comprehension offers a shorter and faster way to do the same task.

Example:

data = {"a": 5, "b": 12, "c": 8}
data = {k: v * 2 if v < 10 else v for k, v in data.items()}
print(data)

This method creates a new dictionary with updated values. It’s faster than loops for large datasets and keeps your code clean and readable.

Updating Values in Lists Within Dictionaries

Accessing List Elements Inside Dictionaries

Sometimes, the values in a dictionary are lists. You can easily access and change items inside those lists by using both the key and the list index.

Example:

data = {"marks": [70, 80, 90]}
data["marks"][1] = 85
print(data)

Output:

{'marks': [70, 85, 90]}

Here, the key “marks” gives access to the list, and [1] points to the second item. This method lets you update or replace specific list elements within a dictionary.

Bulk Operations on List Values

You can also loop through the list elements inside dictionary values to make bulk changes.

Example:

data = {"marks": [70, 80, 90]}
data["marks"] = [m * 1.05 for m in data["marks"]]
print(data)

Output:

{'marks': [73.5, 84.0, 94.5]}

This increases all marks by 5%, showing how to apply one change to every list element at once.

Using Dictionary Comprehensions for Transformations

Syntax Overview

Dictionary comprehensions let you create or modify dictionaries in a single line. The basic syntax is:

data = {k: v * 2 for k, v in data.items()}

This doubles every value in the dictionary. It’s shorter, cleaner, and often faster than using loops.

Conditional Expressions Inside Comprehensions

You can also add conditions inside comprehensions to change only certain values.

Example:

data = {k: v if v > 50 else v + 10 for k, v in data.items()}

This increases values below 50 by 10 but keeps others unchanged. Comprehensions improve readability and performance, making your code more efficient and easy to maintain.

Best Practices for Changing Dictionary Items

When working with dictionaries, following some simple practices helps prevent errors and keeps your code clean:

  • Check if a key exists before updating. Use the in keyword to avoid overwriting or causing errors.
  • Use the update() method for batch updates instead of multiple assignments. It’s cleaner and faster.
  • Be careful when working with nested dictionaries. Use the copy or deepcopy methods from the copy module to avoid unintentional changes in shared data.
  • Avoid modifying a dictionary while looping through it. Instead, create a copy of the dictionary or collect changes separately before applying them.

Common Mistakes to Avoid

    • Using wrong keys. If you try to access a key that doesn’t exist, Python raises a KeyError.
data = {"a": 1}
print(data["b"])  # KeyError
  • Forgetting about nested structures. When dealing with nested dictionaries, overwriting a whole section can remove important inner data.
  • Confusing update() with append(). Dictionaries do not have an append() method. Use update() to add or modify key-value pairs instead.

Conclusion

You’ve now learned the main ways to change dictionary items in Python – using direct assignment, the update() method, and dictionary comprehensions.

Remember, dictionaries are mutable, so you can edit them directly without creating new ones.

Keep experimenting with examples to see how updates, nested changes, and comprehensions behave in different cases. This hands-on practice will make you confident in managing Python dictionaries efficiently.

Related guides

Account services are unavailable until the production backend is configured.