11

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.

so13eit
  • 942
  • 3
  • 11
  • 22
  • That's not even a shallow copy, that's just two references to the same object. A shallow copy would be `itemsChosen.copy()`. – roippi Mar 13 '14 at 20:22
  • 2
    also as an aside... `defaultdict`, like many built-ins, has a copy function: `dupChosen = itemsChosen.copy()`... – Corley Brigman Mar 13 '14 at 20:24
  • Thanks for the clarifications- I misunderstood shallow/deep copying. I also couldn't a page of functions for defaultdict, but that makes sense since it inherits from dict. – so13eit Mar 13 '14 at 20:27

1 Answers1

14

Use copy:

from copy import copy

dupChosen = copy(itemsChosen)

In case of multiple nestings there is also deepcopy.

BoshWash
  • 5,320
  • 4
  • 30
  • 50