Categories
Python Answers

How to copy a dictionary and only edit the copy with Python?

Spread the love

Sometimes, we want to copy a dictionary and only edit the copy with Python.

In this article, we’ll look at how to copy a dictionary and only edit the copy with Python.

How to copy a dictionary and only edit the copy with Python?

To copy a dictionary and only edit the copy with Python, we can use the dict function or the dictionary’s copy method.

For instance, we write:

dict1 = {'a': 1, 'b': 2}

c1 = dict(dict1)
c2 = dict1.copy()

print(c1)
print(c2)

to call dict with dict1 to return a copy of dict1.

Likewise, we call dict1.copy to return a copy of dict1.

Therefore, c1 and c2 are both {'a': 1, 'b': 2}.

Conclusion

To copy a dictionary and only edit the copy with Python, we can use the dict function or the dictionary’s copy method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *