Unwanted behaviour from dict.fromkeys

后端 未结 5 648
感动是毒
感动是毒 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 20:18

    The second argument to dict.fromkeys is just a value. You've created a dictionary that has the same set as the value for every key. Presumably you understand the way this works:

    >>> a = set()
    >>> b = a
    >>> b.add(1)
    >>> b
    set([1])
    >>> a
    set([1])
    

    you're seeing the same behavior there; in your case, x[0], x[1], x[2] (etc) are all different ways to access the exact same set object.

    This is a bit easier to see with objects whose string representation includes their memory address, where you can see that they're identical:

    >>> dict.fromkeys(range(2), object())
    {0: ,
     1: }
    
        

    提交回复
    热议问题