suggestions, comments on an "is_subdict" test

V

Vlastimil Brom

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)doesen't seem to be worth a special check just now.)

Thanks in advance for the suggestions,
regards,
vbr
 
I

Irmen de Jong

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 would use:

test_dct.items() <= base_dct.items()

-irmen
 
R

Raymond Hettinger

In Python 2:

 >>> test_dct = {"foo": 0, "bar": 1}
 >>> base_dct = {"foo": 0, "bar": 1, "baz": 2}
 >>>
 >>> test_dct.items() <= base_dct.items()
False

In Python 3:

 >>> test_dct = {"foo": 0, "bar": 1}
 >>> base_dct = {"foo": 0, "bar": 1, "baz": 2}
 >>> test_dct.items() <= base_dct.items()
True

YMMV

That is because it is spelled differently in Python 2.7:
True

Raymond
 
P

Paul Rubin

Irmen de Jong said:
I would use:
test_dct.items() <= base_dct.items()

I think you need an explicit cast:

set(test_dct.items()) <= set(base_dct.items())
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top