VMware ESXi and vSphere Cluster Management

Modify Dictionary Values in Python

Learn how to read and update existing Python dictionary values, distinguish updates from additions, and safely handle missing keys.

A Python dictionary stores relationships between keys and values. To modify a value, assign a new value to the key that identifies it.

What a Python Dictionary Represents

A dictionary is a mutable Python collection that maps unique keys to values. A key is a hashable identifier used to locate data, and a value is the data associated with that key. Together, a key and its value form a key-value pair.

Dictionaries use curly braces. Each key is followed by a colon and its value:

person = {
    "eye_color": "brown",
    "height": 1.75,
    "weight": 68
}

In this example, "weight" is a key and 68 is its value. The key lets Python find the associated value quickly.

Read an Existing Dictionary Value

Use square brackets containing the key to retrieve a value:

print(person["weight"])

Dictionary access follows the pattern dictionary[key]. It returns the value currently stored for that key.

weight_now = person["weight"]
print(weight_now)  # 68

If the key does not exist, direct access raises a KeyError. A KeyError is an exception that means a requested dictionary key could not be found.

print(person["age"])
# KeyError: 'age'

Update a Value with Item Assignment

Item assignment means assigning a value through square brackets. Use this pattern:

my_dict["key_name"] = new_value

When the key already exists, Python replaces its previous value. Dictionaries are mutable, which means they can be changed after creation. The update changes the existing dictionary in place.

person = {
    "eye_color": "brown",
    "height": 1.75,
    "weight": 68
}

print(person["weight"])

person["weight"] = 70

print(person["weight"])

The first print displays 68, and the second displays 70. The key remains "weight"; only its associated value changes.

Update an Inventory Count

inventory = {
    "notebook": 12,
    "pen": 30,
    "stapler": 4
}

print(inventory["pen"])  # 30
inventory["pen"] = 45
print(inventory["pen"])  # 45

This replaces the stored count for "pen" after new inventory arrives.

Update a Nested Preference

A dictionary value can itself be another dictionary. Use another pair of brackets to update a nested value:

settings = {
    "theme": "light",
    "notifications": {
        "email": True,
        "push": False
    }
}

settings["theme"] = "dark"
settings["notifications"]["push"] = True

print(settings)

The first assignment changes a top-level value. The second assignment changes the "push" value inside the nested "notifications" dictionary.

Updates and Additions Use the Same Syntax

The result of bracket assignment depends on whether the key exists before the assignment.

scores = {
    "math": 80
}

scores["math"] = 95       # Replaces the existing value
scores["science"] = 88    # Adds a new key-value pair

print(scores)

"math" was already present, so its value changed from 80 to 95. "science" was absent, so Python created a new entry.

Dictionary update outcomes

ConditionOperationResult

Key already exists — data["key"] = value — The old value is replaced.

Key does not exist — data["key"] = value — A new key-value pair is added.

Direct lookup of a missing key — data["key"] — A KeyError is raised.

Membership check before update — if "key" in data: — The program can update only when the key is present.

Therefore, bracket assignment does not require a separate update syntax. The difference is determined by the key's existence before assignment.

Choosing a Replacement Value

A dictionary value can be many kinds of Python object. For example, a replacement value may be a string, number, Boolean, list, nested dictionary, or another object.

record = {
    "name": "Mina",
    "age": 25,
    "active": True,
    "tags": ["python", "beginner"],
    "profile": {"level": "basic"}
}

record["name"] = "Mina Lee"          # string
record["age"] = 26                   # number
record["active"] = False             # Boolean
record["tags"] = ["python", "data"] # list
record["profile"] = {"level": "intermediate"} # nested dictionary

Replacing a value can also change its type:

data = {"result": 42}
data["result"] = "forty-two"

Python permits this, but keeping a consistent type for a particular key is often clearer and makes later processing more predictable.

Safely Update a Key When Its Existence Is Uncertain

Use a Membership Test

A membership test uses the in operator to determine whether a key exists in a dictionary:

settings = {
    "theme": "light",
    "language": "English"
}

requested_key = "theme"

if requested_key in settings:
    settings[requested_key] = "dark"
else:
    print("That setting does not exist.")

This approach is useful when the program must update an existing setting but should not accidentally create a new one.

Use get() for Safe Reading

The get() method reads a value without raising a KeyError when the key is absent:

settings = {
    "theme": "light"
}

current_theme = settings.get("theme")
missing_setting = settings.get("font_size")

print(current_theme)     # light
print(missing_setting)   # None

You can provide a default value as a second argument:

font_size = settings.get("font_size", 12)
print(font_size)  # 12

get() is appropriate when a missing key is expected or acceptable and you only need to read the current value. It does not update the dictionary.

Choose Direct Assignment or Validation

  • Use direct assignment such as settings["theme"] = "dark" when the key should already exist or when adding a missing key is acceptable.
  • Use if key in dictionary when updating only known, existing keys matters.
  • Use dictionary.get(key) when you need to read an optional value without a KeyError.

Common Dictionary Operations

GoalSyntax patternEffect

Read an existing value — my_dict["key"] — Returns the value and raises KeyError if the key is missing.

Replace an existing value — my_dict["key"] = new_value — Replaces the value when the key exists.

Add a new key-value pair — my_dict["new_key"] = value — Creates an entry when the key is absent.

Delete a key-value pair — del my_dict["key"] — Removes the entry; the key must exist.

Check whether a key exists — "key" in my_dict — Returns True or False.

Adding and deleting entries are related dictionary operations. This lesson focuses on replacing values for existing keys; use the same distinction between existing and absent keys when learning those operations.

Troubleshooting Dictionary Updates

A KeyError Occurs

The requested key may not be present, or its spelling and capitalization may not exactly match the stored key.

user = {"Name": "Ari"}
print(user["name"])  # KeyError: 'name'

Compare the requested key with the dictionary's keys. Use the exact key, test membership first, or use get() when a missing value is acceptable.

An Expected Update Adds an Item

This usually means the assignment key is different from the existing key because of a typo, different capitalization, or extra whitespace.

settings = {"theme": "light"}
settings["Theme"] = "dark"  # Adds a second key, rather than updating "theme"

print(settings)

Inspect the current keys and use a consistent naming convention.

The Old Value Still Appears

The output may occur before reassignment, the program may be viewing a different dictionary object, or the wrong key may have been updated. Verify execution order, print the complete dictionary after assignment, and confirm both the variable and key.

The Replacement Has an Unexpected Type

Input data may have been supplied as a string instead of the intended numeric or other type.

product = {"stock": 10}
new_stock = "15"
product["stock"] = new_stock

print(type(product["stock"]))  # <class 'str'>

Check the incoming value with type() and convert it when appropriate:

product["stock"] = int(new_stock)
print(product["stock"])  # 15

Key Points to Remember

  • A dictionary maps unique keys to associated values.
  • Read a value with dictionary[key].
  • Assign with dictionary[key] = new_value to replace an existing value.
  • Dictionaries are mutable, so the update changes the dictionary in place.
  • The same assignment syntax adds a new entry when the key does not already exist.
  • Use key in dictionary to check existence before a controlled update.
  • Use dictionary.get(key) to read an optional value without a KeyError.