suggestions, comments on an "is_subdict" test

Raymond Hettinger python at rcn.com
Sat Apr 23 09:23:32 CEST 2011


On Apr 22, 8:18 am, MRAB <pyt... at mrabarnett.plus.com> wrote:
> On 22/04/2011 15:57, Irmen de Jong wrote:
>
>
>
>
>
>
>
> > On 22-4-2011 15:55, 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 would use:
>
> > test_dct.items()<= base_dct.items()
>
> 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:

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

Raymond




More information about the Python-list mailing list