Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #3873 > unrolled thread
| Started by | Peter Otten <__peter__@web.de> |
|---|---|
| First post | 2011-04-22 16:38 +0200 |
| Last post | 2011-04-22 16:38 +0200 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: suggestions, comments on an "is_subdict" test Peter Otten <__peter__@web.de> - 2011-04-22 16:38 +0200
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Date | 2011-04-22 16:38 +0200 |
| Subject | Re: suggestions, comments on an "is_subdict" test |
| Message-ID | <mailman.749.1303483093.9059.python-list@python.org> |
Vlastimil Brom 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.?
> (The builtin exceptions are ok, in case anything not dict-like is
> passed. A cornercase like >>> is_subdict({}, 4)
>>>> True
> doesen't seem to be worth a special check just now.)
I would avoid the unique object because it's neither hard nor costly:
def is_subdict(test, base):
return all(k in base and base[k] == v for k, v in test.iteritems())
Back to top | Article view | comp.lang.python
csiph-web