杰瑞科技汇

python update dict

Of course! Updating a dictionary in Python is a common task. There are several ways to do it, each with its own use case. Here’s a comprehensive guide covering the most common methods, from simple to more advanced.

python update dict-图1
(图片来源网络,侵删)

Summary of Methods

Method What it Does Example When to Use
dict.update() Updates the dictionary in-place with key/value pairs from another object. my_dict.update(new_items) The standard, most efficient way to update one dict with another.
Unpacking ``** Creates a new dictionary by merging others. Does not modify the original. merged_dict = {**dict1, **dict2} When you need a new merged dictionary and want to keep the originals unchanged.
Dictionary Comprehension Creates a new dictionary by iterating and transforming an existing one. {k: v*2 for k, v in my_dict.items()} When you need to transform keys, values, or filter items while updating.
Loops Gives you full, explicit control over the update process. for key, value in items: ... For complex, conditional logic where simple updates aren't enough.

Method 1: The dict.update() Method (Most Common)

This is the most direct and efficient way to update a dictionary. It modifies the dictionary in-place, meaning it doesn't return a new dictionary but changes the original one.

Syntax

my_dict.update(other_dict)
# or
my_dict.update(key1=value1, key2=value2)

How it Works:

  • If a key from other_dict is already in my_dict, its value is overwritten.
  • If a key from other_dict is not in my_dict, it is added.
  • It handles different data types for other_dict (another dict or an iterable of key/value pairs).

Example 1: Updating with another dictionary

# Original dictionary
student = {'name': 'Alice', 'age': 25, 'major': 'Biology'}
# Dictionary with updates
updates = {'age': 26, 'major': 'Physics', 'graduation_year': 2025}
# Update the original dictionary
student.update(updates)
print(student)
# Output: {'name': 'Alice', 'age': 26, 'major': 'Physics', 'graduation_year': 2025}

Notice how 'age' and 'major' were updated, and 'graduation_year' was added.

Example 2: Updating with keyword arguments

This is a clean way to add or update a few specific items.

# Original dictionary
user_settings = {'theme': 'dark', 'notifications': True}
# Update using keyword arguments
user_settings.update(language='Python', font_size=14)
print(user_settings)
# Output: {'theme': 'dark', 'notifications': True, 'language': 'Python', 'font_size': 14}

Important Note: In-Place Modification

update() changes the original dictionary. If you need to keep the original, you must make a copy first.

python update dict-图2
(图片来源网络,侵删)
original = {'a': 1, 'b': 2}
update_data = {'b': 3, 'c': 4}
# Make a copy before updating
new_dict = original.copy()
new_dict.update(update_data)
print("Original:", original)  # Unchanged
# Output: Original: {'a': 1, 'b': 2}
print("New Dict:", new_dict)
# Output: New Dict: {'a': 1, 'b': 3, 'c': 4}

Method 2: Dictionary Unpacking () (Python 3.5+)

This method creates a new dictionary by merging two or more existing ones. The original dictionaries are not modified.

Syntax

new_dict = {**dict1, **dict2, **dict3}

If a key exists in multiple dictionaries, the value from the last dictionary in the sequence wins.

Example

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'c': 5, 'd': 6}
# Create a new merged dictionary
merged_dict = {**dict1, **dict2, **dict3}
print("Original dict1:", dict1) # Unchanged
# Output: Original dict1: {'a': 1, 'b': 2}
print("Original dict2:", dict2) # Unchanged
# Output: Original dict2: {'b': 3, 'c': 4}
print("Merged Dictionary:", merged_dict)
# Output: Merged Dictionary: {'a': 1, 'b': 3, 'c': 5, 'd': 6}

Here, 'b' came from dict2 (overwriting dict1's value) and 'c' came from dict3 (overwriting dict2's value).


Method 3: Dictionary Comprehension

This is not for "merging" but for creating a new dictionary based on the transformation of an existing one. It's extremely powerful for updates that require logic.

Syntax

new_dict = {key: expression for key, value in old_dict.items()}

Example 1: Updating all values

Let's say you want to double all the numeric values in a dictionary.

scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Create a new dictionary with all values doubled
updated_scores = {name: score * 2 for name, score in scores.items()}
print("Original:", scores)
# Output: Original: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print("Updated:", updated_scores)
# Output: Updated: {'Alice': 170, 'Bob': 184, 'Charlie': 156}

Example 2: Conditional Updates (Filtering)

Let's update only the scores that are below 80, adding a bonus.

scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78}
# Add a 10-point bonus to scores below 80
updated_scores = {
    name: score + 10 if score < 80 else score
    for name, score in scores.items()
}
print("Original:", scores)
# Output: Original: {'Alice': 85, 'Bob': 92, 'Charlie': 78}
print("Updated:", updated_scores)
# Output: Updated: {'Alice': 85, 'Bob': 92, 'Charlie': 88}

Method 4: Using a for Loop (For Maximum Control)

This is the most manual method but gives you complete control, especially for complex or conditional logic.

Example: Conditional Updates

Let's update a dictionary, but only if the new value is an integer and greater than the existing one.

inventory = {'apple': 50, 'banana': 120, 'orange': 75}
restock = {'apple': 60, 'banana': 'low', 'grape': 200}
for key, value in restock.items():
    # Check if the key exists in the inventory AND the new value is an integer
    if key in inventory and isinstance(value, int):
        # Only update if the new value is greater
        if value > inventory[key]:
            inventory[key] = value
    # If the key doesn't exist, add it (and ensure value is int)
    elif isinstance(value, int):
        inventory[key] = value
print(inventory)
# Output: {'apple': 60, 'banana': 120, 'orange': 75, 'grape': 200}

In this example, 'banana' was not updated because its new value was a string, and 'grape' was added.

Which Method Should I Choose?

  • To update an existing dictionary in-place: Use my_dict.update(). It's fast, idiomatic, and clear.
  • To create a new, merged dictionary without changing the originals: Use dictionary unpacking ({**d1, **d2}). It's concise and readable for a small number of dicts.
  • To transform values or filter items based on a rule: Use a dictionary comprehension. It's Pythonic and efficient for this specific task.
  • For complex, conditional logic that update() or comprehensions can't handle: Use a for loop. It gives you the ultimate flexibility.
分享:
扫描分享到社交APP
上一篇
下一篇