KeyError with dict.fromkeys () and dict-like object

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)?

+3
source share
2 answers

To create a dict, fromkeysiterates over its argument. So it must be an iterator. One way to make it work is to add a method __iter__to your dict-like:

def __iter__(self):
    return iter(self.d)
+6
source

SemiDict . , dict, ?

+1

Source: https://habr.com/ru/post/1719091/


All Articles