suggestions, comments on an "is_subdict" test
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Apr 22 19:52:25 EDT 2011
On Fri, 22 Apr 2011 07:38:38 -0700, Chris Rebert wrote:
> Also, the following occurs to me as another idiomatic, perhaps more
> /conceptually/ elegant possibility, but it's /practically/ speaking
> quite inefficient (unless perhaps some dict view tricks can be
> exploited):
>
> def is_subdict(sub, larger):
> return set(sub.items()).issubset(set(larger.items()))
That cannot work if either dict contains an unhashable value:
>>> d = {2: []}
>>> set(d.items())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
But if you know your dict items are hashable, and your dicts not
especially large, I don't see why we should fear the inefficiency of
turning them into sets. Worrying about small efficiencies is usually
counter-productive, especially in a language like Python that so often
trades off machine efficiency for developer efficiency.
--
Steven
More information about the Python-list
mailing list