Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 23287

Peter Bengtsson: Be careful with using dict() to create a copy

$
0
0

Everyone who's done Python for a while soon learns that dicts are mutable. I.e. that they can change.

One way of "forking" a dictionary into two different ones is to create a new dictionary object with dict(). E.g:

>>>first={'key':'value'}>>>second=dict(first)>>>second['key']='other'>>>first{'key':'value'}>>>second{'key':'other'}

See, you can change the value of a key without affecting the dictionary it came from.

But, if one of the values is also mutable, beware!

>>>first={'key':['value']}>>>second=dict(first)>>>second['key'].append('second value')>>>first{'key':['value','second value']}>>>second{'key':['value','second value']}

This is where you need to use the built in copy.deepcopy.

>>>importcopy>>>first={'key':['value']}>>>second=copy.deepcopy(first)>>>second['key'].append('second value')>>>first{'key':['value']}>>>second{'key':['value','second value']}

Yay! Hope it helps someone avoid some possibly confusing bugs some day.

UPDATE

As ëRiC reminded me, there are actually three ways to make a "shallow copy" of a dictionary:

1) some_copy = dict(some_dict)

2) some_copy = some_dict.copy()

3) some_copy = copy.copy(some_dict) # after importing 'copy'


Viewing all articles
Browse latest Browse all 23287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>