Copying a dictionary allows you to create a new dictionary with the same key-value pairs as the original dictionary. In this blog post, we will explore different methods to copy a dictionary in Python.
Method 1: Using the copy() Method
# Method 1: Using the copy() Method my_dict = {"name": "John", "age": 30, "city": "New York"} copy_dict = my_dict.copy() print("Copied dictionary:", copy_dict)
Output:
Copied dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}
Method 2: Using the dict() Constructor
# Method 2: Using the dict() Constructor my_dict = {"name": "John", "age": 30, "city": "New York"} copy_dict = dict(my_dict) print("Copied dictionary:", copy_dict)
Output:
Copied dictionary: {‘name’: ‘John’, ‘age’: 30, ‘city’: ‘New York’}