杰瑞科技汇

Python字典合并有哪些常用方法?

Of course! Merging dictionaries in Python is a common task. The best method to use depends on your Python version and whether you need to create a new dictionary or modify an existing one.

Here’s a comprehensive guide, starting with the modern and recommended approaches.

Summary: Quick Answer

For most modern Python (3.9+), the best way to merge two or more dictionaries into a new one is:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# The recommended way (Python 3.9+)
merged_dict = dict1 | dict2
print(merged_dict)
# Output: {'a': 1, 'b': 3, 'c': 4}

For modifying an existing dictionary in-place (Python 3.9+):

dict1 |= dict2
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}

Detailed Guide with Examples

Let's use these two example dictionaries for all our examples:

dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
dict3 = {'d': 5}

Method 1: Dictionary Unpacking (Python 3.5+)

This is a very popular and readable way to merge dictionaries. You unpack the key-value pairs from each dictionary into a new dictionary literal.

To create a new dictionary:

# Merge two dicts
merged = {**dict1, **dict2}
print(merged)
# Output: {'a': 1, 'b': 3, 'c': 4}
# Merge three dicts
merged_all = {**dict1, **dict2, **dict3}
print(merged_all)
# Output: {'a': 1, 'b': 3, 'c': 4, 'd': 5}

How it works: The later dictionaries' keys overwrite the earlier ones. In {**dict1, **dict2}, dict2 comes after dict1, so its value for key 'b' (3) overwrites the value from dict1 (2).

To update an existing dictionary in-place:

You can combine unpacking with the update() method.

# dict1 is {'a': 1, 'b': 2}
dict1.update({**dict2, **dict3})
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4, 'd': 5}

Method 2: The and Operators (Python 3.9+)

This is the newest, most concise, and arguably the most elegant syntax introduced in Python 3.9.

  • (union operator): Creates a new dictionary.
  • (in-place union operator): Updates the dictionary in-place.

To create a new dictionary:

# Merge two dicts
merged = dict1 | dict2
print(merged)
# Output: {'a': 1, 'b': 3, 'c': 4}
# Merge three dicts
merged_all = dict1 | dict2 | dict3
print(merged_all)
# Output: {'a': 1, 'b': 3, 'c': 4, 'd': 5}

To update an existing dictionary in-place:

# dict1 is {'a': 1, 'b': 2}
dict1 |= dict2
print(dict1)
# Output: {'a': 1, 'b': 3, 'c': 4}

Method 3: The update() Method (Classic, In-Place)

This is the traditional way to merge dictionaries. It modifies the dictionary in-place and returns None. This is a key difference from the other methods.

To update an existing dictionary:

# Start with a fresh dict1
dict1 = {'a': 1, 'b': 2}
# dict2 is {'b': 3, 'c': 4}
result = dict1.update(dict2)
# update() modifies dict1 directly and returns None
print(f"Result of update(): {result}")
# Output: Result of update(): None
print(f"dict1 after update(): {dict1}")
# Output: dict1 after update(): {'a': 1, 'b': 3, 'c': 4}

How it works: update() adds key-value pairs from the second dictionary. If a key already exists, its value is overwritten.

To merge multiple dictionaries with update():

You can chain update() calls.

dict1 = {'a': 1, 'b': 2}
dict1.update(dict2) # dict1 is now {'a': 1, 'b': 3, 'c': 4}
dict1.update(dict3) # dict1 is now {'a': 1, 'b': 3, 'c': 4, 'd': 5}
print(dict1)

Method 4: collections.ChainMap (Advanced Use Case)

ChainMap doesn't actually merge the dictionaries. Instead, it creates a view that looks like a single dictionary but chains multiple dictionaries together. It's very useful for looking up keys in several dictionaries without creating a merged copy.

from collections import ChainMap
# Create a ChainMap
chained = ChainMap(dict1, dict2)
# Look up a key
print(chained['a']) # Found in dict1
# Output: 1
print(chained['b']) # Found in dict2 (it comes first in the chain)
# Output: 3
print(chained['c']) # Found in dict2
# Output: 4
# If you modify a key in the ChainMap, it goes into the FIRST dictionary
chained['a'] = 99
print(dict1)
# Output: {'a': 99, 'b': 2}  # dict1 was modified

Comparison Table

Method Python Version Creates New Dict? Behavior on Key Conflict Readability
dict1 | dict2 9+ Yes Right-hand side wins Excellent
`{d1, d2}` 5+ Yes Right-hand side wins Excellent
d1.update(d2) All No (In-place) d2's value wins Good
collections.ChainMap All No (View) First occurrence wins Good (for its purpose)

Which One Should I Use?

  • If you are using Python 3.9 or newer:

    • To create a new merged dictionary, use the operator: merged = dict1 | dict2. It's clean, fast, and the modern standard.
    • To update a dictionary in-place, use : dict1 |= dict2.
  • If you are using Python 3.5 to 3.8:

    • To create a new merged dictionary, use unpacking: merged = {**dict1, **dict2}. This is the most common and readable pre-3.9 method.
    • To update a dictionary in-place, use update(): dict1.update(dict2).
  • If you need to preserve the original dictionaries: Always use a method that creates a new dictionary ( or ). Never use update() or if you need to keep the original dict unchanged.

  • If you are working with older Python versions (< 3.5): Your best option is the update() method for in-place merging or creating a new dictionary manually in a loop.

分享:
扫描分享到社交APP
上一篇
下一篇