📜  Python|复制字典的方法

📅  最后修改于: 2022-05-13 01:54:46.605000             🧑  作者: Mango

Python|复制字典的方法

字典是一个无序、可变和索引的集合。在Python中,字典是用大括号编写的,它们有键和值。它广泛用于日常编程、Web 开发和机器学习。当我们简单地分配 dict1 = dict2 时,它指的是同一个字典。让我们讨论几种从另一个字典复制字典的方法。方法#1:使用copy()
copy()方法返回字典的浅拷贝。
它不带任何参数并返回一个不引用初始字典的新字典。

# Python3 code to demonstrate
# how to copy dictionary
# using copy() function
  
  
# initialising dictionary
test1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"}
  
  
# method to copy dictionary using copy() function
test2 = test1.copy()
  
  
# updating test2
test2["name1"] ="nikhil"
  
# print initial dictionary
print("initial dictionary = ", test1)
  
# printing updated dictionary
print("updated dictionary = ", test2)

输出

initial dictionary =  {'name1': 'manjeet', 'name2': 'vashu', 'name': 'akshat'}
updated dictionary =  {'name1': 'nikhil', 'name': 'akshat', 'name2': 'vashu'}

方法 #2:使用dict()
dict()是一个在Python中创建字典的构造函数。

# Python3 code to demonstrate
# how to copy dictionary
# using dict()
  
  
# initialising dictionary
test1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"}
  
  
# method to copy dictionary using dict
test2 = dict(test1)
  
  
# updating test2
test2["name1"] ="nikhil"
  
# print initial dictionary
print("initial dictionary = ", test1)
  
# printing updated dictionary
print("updated dictionary = ", test2)

输出

initial dictionary =  {'name2': 'vashu', 'name': 'akshat', 'name1': 'manjeet'}
updated dictionary =  {'name2': 'vashu', 'name': 'akshat', 'name1': 'nikhil'}

方法#3:使用字典理解

# Python3 code to demonstrate
# how to copy dictionary
# using dictionary comprehension
  
  
# initialising dictionary
test1 = {"name" : "akshat", "name1" : "manjeet", "name2" : "vashu"}
  
  
# method to copy dictionary using dictionary comprehension
test2 = {k:v for k, v in test1.items()}
  
  
# updating test2
test2["name1"] ="ayush"
  
# print initial dictionary
print("initial dictionary = ", test1)
  
# printing updated dictionary
print("updated dictionary = ", test2)

输出

initial dictionary =  {'name': 'akshat', 'name2': 'vashu', 'name1': 'manjeet'}
updated dictionary =  {'name': 'akshat', 'name2': 'vashu', 'name1': 'ayush'}