Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python copying or cloning a defaultdict variable

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.

like image 563
so13eit Avatar asked Mar 13 '14 20:03

so13eit


1 Answers

Use copy:

from copy import copy

dupChosen = copy(itemsChosen)

In case of multiple nestings there is also deepcopy.

like image 175
BoshWash Avatar answered Oct 17 '22 10:10

BoshWash