Unwanted behaviour from dict.fromkeys

后端 未结 5 651
感动是毒
感动是毒 2020-11-27 19:36

I\'d like to initialise a dictionary of sets (in Python 2.6) using dict.fromkeys, but the resulting structure behaves strangely. More specifically:



        
5条回答
  •  一个人的身影
    2020-11-27 19:59

    The reason its working this way is that set([]) creates an object (a set object). Fromkeys then uses that specific object to create all its dictionary entries. Consider:

    >>> x
    {0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 
    6: set([]), 7: set([]), 8: set([]), 9: set([])}
    >>> x[0] is x[1]
    True
    

    All the sets are the same!

提交回复
热议问题