杰瑞科技汇

Python如何深拷贝字典?

Of course! In Python, creating a "clone" of a dictionary means creating a new dictionary object that contains the same key-value pairs as the original. The crucial point is understanding whether you need a shallow copy or a deep copy.

Python如何深拷贝字典?-图1
(图片来源网络,侵删)

Here's a breakdown of the different methods, from the most common to the more specialized.

TL;DR: Quick Answer

For most use cases, use the copy() method or the dict() constructor.

original = {'a': 1, 'b': 2}
# Method 1: Using the .copy() method (most common)
shallow_copy_1 = original.copy()
# Method 2: Using the dict() constructor
shallow_copy_2 = dict(original)
# Both are equivalent for this simple case
print(shallow_copy_1)  # Output: {'a': 1, 'b': 2}
print(shallow_copy_2)  # Output: {'a': 1, 'b': 2}

Shallow Copy

A shallow copy creates a new dictionary object, but it does not create copies of the objects stored within the dictionary. Instead, the new dictionary contains references to the same objects as the original dictionary.

This is fine if your dictionary contains only immutable objects like numbers, strings, or tuples. It becomes a problem if it contains mutable objects like lists or other dictionaries.

Python如何深拷贝字典?-图2
(图片来源网络,侵删)

How to Create a Shallow Copy

Method 1: The .copy() Method (Recommended) This is the most readable and Pythonic way to create a shallow copy.

original = {'name': 'Alice', 'scores': [88, 92, 95]}
shallow_copy = original.copy()
# Modifying the new dictionary's key works independently
shallow_copy['name'] = 'Bob'
print(f"Original name: {original['name']}")      # Output: Original name: Alice
print(f"Copy name: {shallow_copy['name']}")        # Output: Copy name: Bob
# Modifying the mutable object (list) inside the copy affects the original!
shallow_copy['scores'].append(100)
print(f"Original scores: {original['scores']}")  # Output: Original scores: [88, 92, 95, 100]
print(f"Copy scores: {shallow_copy['scores']}")    # Output: Copy scores: [88, 92, 95, 100]

Method 2: The dict() Constructor This is another very common and clear way to achieve the same result.

original = {'name': 'Alice', 'scores': [88, 92, 95]}
shallow_copy = dict(original)

Method 3: The Dictionary Unpacking Operator (``)** This is a modern, concise way available in Python 3.5+. It's very popular for creating new dictionaries with modifications.

original = {'name': 'Alice', 'scores': [88, 92, 95]}
shallow_copy = {**original}
# You can also use it to create a copy and add/modify items in one line
modified_copy = {**original, 'name': 'Bob', 'grade': 'A'}
print(modified_copy) # Output: {'name': 'Bob', 'scores': [88, 92, 95], 'grade': 'A'}

Method 4: The copy Module The standard library's copy module has a copy() function that can be used for general shallow copying.

Python如何深拷贝字典?-图3
(图片来源网络,侵删)
import copy
original = {'name': 'Alice', 'scores': [88, 92, 95]}
shallow_copy = copy.copy(original)

Deep Copy

A deep copy creates a new dictionary object and recursively creates new copies of all objects found within the original dictionary. The new dictionary and its contents are completely independent of the original.

You should use a deep copy when you need to work with a dictionary that contains mutable objects (like lists or dicts) and you want to ensure that changes to the copy do not affect the original in any way.

How to Create a Deep Copy

Method: The copy.deepcopy() Function This is the standard and only way to create a true deep copy.

import copy
original = {'name': 'Alice', 'scores': [88, 92, 95]}
deep_copy = copy.deepcopy(original)
# Modifying the new dictionary's key works independently
deep_copy['name'] = 'Bob'
print(f"Original name: {original['name']}")      # Output: Original name: Alice
print(f"Copy name: {deep_copy['name']}")          # Output: Copy name: Bob
# Modifying the mutable object (list) inside the deep copy does NOT affect the original!
deep_copy['scores'].append(100)
print(f"Original scores: {original['scores']}")  # Output: Original scores: [88, 92, 95]
print(f"Copy scores: {deep_copy['scores']}")    # Output: Copy scores: [88, 92, 95, 100]

Performance Consideration

Deep copying is computationally more expensive than shallow copying, especially for large and complex data structures. Only use it when you truly need the complete independence of objects.


Comparison Table

Method Type of Copy Use Case Example
dict.copy() Shallow Most common case. For dictionaries with immutable values (int, str, tuple) or when you intentionally want shared mutable objects. new_dict = my_dict.copy()
dict(original) Shallow Same as .copy(). A good alternative, especially when converting other mappings to dicts. new_dict = dict(my_dict)
`{original}`** Shallow Modern and concise. Excellent for creating a copy with modifications. new_dict = {**my_dict, 'new_key': 'new_val'}
copy.copy() Shallow General-purpose shallow copy. Works for any object, not just dicts. import copy; new_dict = copy.copy(my_dict)
copy.deepcopy() Deep When you have nested mutable objects (lists, dicts) and need the copy to be completely independent. import copy; new_dict = copy.deepcopy(my_dict)

What About (Assignment Operator)?

This is a common point of confusion. The operator does not create a copy. It creates a new reference to the exact same dictionary object in memory.

original = {'a': 1, 'b': [2, 3]}
# This is NOT a copy. This is an alias.
alias = original
# Modifying the alias modifies the original dictionary
alias['a'] = 99
print(original)  # Output: {'a': 99, 'b': [2, 3]}
# They are the same object in memory
print(alias is original)  # Output: True

Summary and Recommendation

  1. For simple dictionaries (with numbers, strings, etc.) or when you want to share mutable objects, use a shallow copy.

    • Best choice: my_dict.copy()
    • Good alternatives: dict(my_dict) or {**my_dict}
  2. For dictionaries with nested mutable objects (like lists or other dictionaries) where you need complete independence, use a deep copy.

    • Only choice: import copy; copy.deepcopy(my_dict)
  3. Never use if you want a new, independent dictionary.

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