suggestions, comments on an "is_subdict" test

Peter Otten __peter__ at web.de
Fri Apr 22 19:30:59 CEST 2011


Zero Piraeus wrote:

>>> Anything wrong with this?
>>>
>>> def is_subdict(test_dct, base_dct):
>>> return test_dct <= base_dct and all(test_dct[k] == base_dct[k] for
>>> k in test_dct)
>>
>> It may raise a KeyError.
> 
> Really? That was what ``test_dct <= base_dct and`` ... is supposed to
> prevent. Have I missed something?

>>> {1:0} <= {2:0}
True
>>> def is_subdict(test_dct, base_dct):
...     return test_dct <= base_dct and all(test_dct[k] == base_dct[k] for
... k in test_dct)
...
>>> is_subdict({1:0}, {2:0})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in is_subdict
  File "<stdin>", line 3, in <genexpr>
KeyError: 1

I think you have to convert to sets before performing the <= comparison to 
get a proper subset test.




More information about the Python-list mailing list