Unwanted behaviour from dict.fromkeys

后端 未结 5 642
感动是毒
感动是毒 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:04

    
    #To do what you want:
    
    import copy
    s = set([])
    x = {}
    for n in range(0,5):
      x[n] = copy.deepcopy(s)
    x[2].add(3)
    print x
    
    #Printing
    #{0: set([]), 1: set([]), 2: set([3]), 3: set([]), 4: set([])}
    

提交回复
热议问题