在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)?
要创建dict,请fromkeys遍历其参数.所以它必须是一个迭代器.使其工作的一种__iter__方法是为您添加一个方法dict:
def __iter__(self):
return iter(self.d)
Run Code Online (Sandbox Code Playgroud)