How can I make a duplicate copy (not just assigning a new pointer to the same location in memory) of Python's defaultdict object?
from collections import defaultdict
itemsChosen = defaultdict(list)
itemsChosen[1].append(1)
dupChosen = itemsChosen
itemsChosen[2].append(1)
print dupChosen
What the code above does is a shallow copy and returns
defaultdict(<type 'list'>, {1: [1], 2: [1]})
whereas what I'm looking for it to return
defaultdict(<type 'list'>, {1: [1]})
Thanks.
Use copy:
from copy import copy
dupChosen = copy(itemsChosen)
In case of multiple nestings there is also deepcopy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With