In Python, you can use a dictionary as the first argument to dict.fromkeys(), for example:
In [1]: d = {'a': 1, 'b': 2}
In [2]: dict.fromkeys(d)
Out[2]: {'a': None, 'b': None}
I tried to do the same with a dictate-like object, but it always raises the value KeyError, for example:
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
What exactly is going on here? And can this be solved, besides using something like dict.fromkeys(sd.d)?
source
share