与dict.fromkeys()和类似dict的对象的KeyError

Raf*_*afG 3 python dictionary

在Python中,您可以使用字典作为第一个参数dict.fromkeys(),例如:

In [1]: d = {'a': 1, 'b': 2}

In [2]: dict.fromkeys(d)
Out[2]: {'a': None, 'b': None}
Run Code Online (Sandbox Code Playgroud)

我尝试用类似dict的对象做同样的事情,但总是引发一个KeyError,例如:

In [1]: class SemiDict:
   ...:     def __init__(self):
   ...:         self.d = {}
   ...:
   ...:     def __getitem__(self, key):
   ...:         return self.d[key]
   ...:
   ...:     def __setitem__(self, key, value):
   ...:         self.d[key] = value
   ...:
   ...:

In [2]: sd = SemiDict()

In [3]: sd['a'] = 1

In [4]: dict.fromkeys(sd)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)

C:\bin\Console2\<ipython console> in <module>()

C:\bin\Console2\<ipython console> in __getitem__(self, key)

KeyError: 0
Run Code Online (Sandbox Code Playgroud)

到底发生了什么?它可以解决,除了使用类似的东西dict.fromkeys(sd.d)

nos*_*klo 6

要创建dict,请fromkeys遍历其参数.所以它必须是一个迭代器.使其工作的一种__iter__方法是为您添加一个方法dict:

def __iter__(self):
    return iter(self.d)
Run Code Online (Sandbox Code Playgroud)

  • 它应该被添加,在没有`__iter__`的情况下,它将像序列一样访问它,调用`__getitem __(0)`,然后调用1,依此类推.因此KeyError为0. (3认同)