Categories
Python Answers

How to make a copy of dicts on assignment with Python?

Spread the love

Sometimes, we want to make a copy of dicts on assignment with Python.

In this article, we’ll look at how to make a copy of dicts on assignment with Python.

How to make a copy of dicts on assignment with Python?

To make a copy of dicts on assignment with Python, we can call the copy method.

For instance, we write:

a = {'foo': 2}
b = a.copy()
b['bar'] = 3

print(a)
print(b)

We call a.copy to make a copy of a and assign it to b.

Then we added a new entry with key 'bar' to b.

Since we made a copy of a and assigned that to b, a is unchanged when we changed b.

So a is {'foo': 2} and b is {'foo': 2, 'bar': 3}.

Conclusion

To make a copy of dicts on assignment with Python, we can call the 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 *