What is copy dictionary ?
In Python, a copy of a dictionary is a new dictionary that contains the same key-value pairs as the original dictionary. The copy is not linked to the original dictionary, which means that changes made to one dictionary will not affect the other.
Copy Dictionary Basic Syntax:
If you want to copy a dictionary in Python, you can use the copy() method basic syntax are the following.
# create original_dict copy
copy_dict = original_dict.copy()
In Python, you can create a copy of a dictionary using either the copy() method.
For Example:
new_dict = dict.copy()
print(new_dict)
Output is : {id: 100, 'name': 'Arsalan', 'field': 'data analytics'}
If We don't use copy() method:
If you assign a dictionary to a new variable without using the copy() method, the new variable will reference the same dictionary object in memory. Therefore, any changes made to one variable will also affect the other variable.
For Example:
copy_dict = original_dict
# remove id key-value pair in copy_dict
copy_dict.pop(id)
# print original dictionary
print(original_dict)
# print dublicate/copy dictionary
print(copy_dict)
Output for original dictionary :{'name': 'Arsalan', 'field': 'Analytics'}
Output for copy dictionary : {'name': 'Arsalan', 'field': 'Analytics'}
Note 👇👇👇
In this Example : We assign original_dict to copy_dict without using copy(). When we remove id key-value pair in copy_dict, it also remove in original_dict, because both variables reference the same dictionary object. To avoid this issue, you can use copy() to create a new dictionary object that is not linked to the original dictionary.How to print key-value pairs?
If you want to print the keys and values of a dictionary, you can use a keys() and values() method.
keys() Method:
dict = {id : 100, "name" : "Arsalan", "field" : "data analytics"}
print(dict.keys())
Output is : dict_keys([id, 'name', 'field'])
values() Method:
dict = {id : 100, "name" : "Arsalan", "field" : "data analytics"}
print(dict.values())
Output is : dict_values([100, 'Arsalan', 'data analytics'])
If you want to print both the keys and values of a dictionary, you can use a for loop to iterate over the dictionary items, and then print each key-value pair using string formatting.
For Example :
for key, value in dict.items():
print(f"{key}: {value}")
Output is 👇👇👇
name: Arsalan
field: data analytics
LIKE SHARE AND SUBSCRIBE