Unwanted behaviour from dict.fromkeys
Posted
by Anthony Labarre
on Stack Overflow
See other posts from Stack Overflow
or by Anthony Labarre
Published on 2010-06-08T19:14:37Z
Indexed on
2010/06/09
7:02 UTC
Read the original article
Hit count: 222
python
Hi there,
I'd like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys
, but the resulting structure behaves strangely. More specifically:
>>>> x = {}.fromkeys(range(10), set([]))
>>>> x
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])}
>>>> x[5].add(3)
>>>> x
{0: set([3]), 1: set([3]), 2: set([3]), 3: set([3]), 4: set([3]), 5: set([3]), 6: set([3]), 7: set([3]), 8: set([3]), 9: set([3])}
I obviously don't want to add 3 to all sets, only to the set that corresponds to x[5]
. Of course, I can avoid the problem by initialising x
without fromkeys
, but I'd like to understand what I'm missing here.
© Stack Overflow or respective owner