Search code examples
pythonpython-2.7dictionarycopydefaultdict

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.


Solution

  • Use copy:

    from copy import copy
    
    dupChosen = copy(itemsChosen)
    

    In case of multiple nestings there is also deepcopy.