How to assert a dict contains another dict without assertDictContainsSubset in python?

JerryCai picture JerryCai · Jan 11, 2014 · Viewed 29.1k times · Source

I know assertDictContainsSubset can do this in python 2.7, but for some reason it's deprecated in python 3.2. So is there any way to assert a dict contains another one without assertDictContainsSubset?

This seems not good:

for item in dic2:
    self.assertIn(item, dic)

any other good way? Thanks

Answer

John1024 picture John1024 · Jan 11, 2014
>>> d1 = dict(a=1, b=2, c=3, d=4)
>>> d2 = dict(a=1, b=2)
>>> set(d2.items()).issubset( set(d1.items()) )
True

And the other way around:

>>> set(d1.items()).issubset( set(d2.items()) )
False

Limitation: the dictionary values have to be hashable.