学习Python dict.copy()方法

339 阅读1分钟

摘要:在 Python 中有许多不同的方法来复制字典数据结构对象。在本教程中,我将向你展示内置的dict.copy() 方法,它是复制字典的一个非常有用的方法。

定义:每当对一个 dictionary 应用dict.copy() 方法时,就会产生一个新的 dictionary,它包含对原始 dictionary 的引用的拷贝。

Python 的 dict.copy() 方法的语法

方法声明dict.copy()

dict.copy()

方法参数dict.copy()

Python 的dict.copy() 方法不输入任何参数。

方法返回值dict.copy()

dict.copy() 方法输出一个字典的浅层拷贝,也就是说,它复制了字典结构,但是克隆的字典结构仍然指的是原始对象的元素。

使用 dict.copy() 方法的基本例子

original_dict = {'ebook': 'python-book',
                 'video': 'freelance-video',
                 'computer': 'laptop'}

new_dict = original_dict.copy()

print('original dictionary: ', original_dict)
print('new dictionary: ', new_dict)

# Note: the 2 outputs will be the same.

输出

original dictionary:  {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'}
new dictionary:  {'ebook': 'python-book', 'video': 'freelance-video', 'computer': 'laptop'}

字典dict.copy() vs 赋值=运算符

  • dict.copy() 方法应用于一个字典时,会产生一个新的字典,它包含了原字典的引用。
  • 等价 = 操作符被应用时,会产生一个对原始字典的新引用。

使用=运算符的例子。

grocery_dict = {'juice': 'apple',
                'drink': 'tea',
                'fruit': 'melon'}

new_grocery = grocery_dict
new_grocery.clear()

print('original grocery dict: ', grocery_dict)
print('original grocery dict: ', grocery_dict)

# Note: outputs are both an empty dictionary: {}

输出

original grocery dict:  {}
original grocery dict:  {}