Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3874

Re: suggestions, comments on an "is_subdict" test

References <BANLkTinazu41uVqxmkfTns0ZOHScZ1a3nQ@mail.gmail.com>
Date 2011-04-22 07:38 -0700
Subject Re: suggestions, comments on an "is_subdict" test
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.750.1303483120.9059.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Apr 22, 2011 at 6:55 AM, Vlastimil Brom
<vlastimil.brom@gmail.com> wrote:
> Hi all,
> I'd like to ask for comments or advice on a simple code for testing a
> "subdict", i.e. check whether all items of a given dictionary are
> present in a reference dictionary.
> Sofar I have:
>
> def is_subdict(test_dct, base_dct):
>    """Test whether all the items of test_dct are present in base_dct."""
>    unique_obj = object()
>    for key, value in test_dct.items():
>        if not base_dct.get(key, unique_obj) == value:
>            return False
>    return True
>
> I'd like to ask for possibly more idiomatic solutions, or more obvious
> ways to do this. Did I maybe missed some builtin possibility?
> I am unsure whether the check  against an unique object() or the
> negated comparison are usual.?

I second MRAB's all() suggestion. The use of object() as a higher-rank
None is entirely normal; don't worry about it.

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

Cheers,
Chris

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: suggestions, comments on an "is_subdict" test Chris Rebert <clp2@rebertia.com> - 2011-04-22 07:38 -0700
  Re: suggestions, comments on an "is_subdict" test Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-04-22 23:52 +0000

csiph-web