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

>>> 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.


Although I'm using pytest, I found the following idea in a comment. It worked really great for me, so I thought it could be useful here:

assert dict1.items() <= dict2.items()

for Python 3 and

assert dict1.viewitems() <= dict2.viewitems()

for Python 2.

It works with non-hashable items, but you can't know exactly which item eventually fails.


The big problem with the accepted answer is that it does not work if you have non hashable values in your objects values. The second thing is that you get no useful output - the test passes or fails but doesn't tell you which field within the object is different.

As such it is easier to simply create a subset dictionary then test that. This way you can use the TestCase.assertDictEquals() method which will give you very useful formatted output in your test runner showing the diff between the actual and the expected.

I think the most pleasing and pythonic way to do this is with a simple dictionary comprehension as such:

from unittest import TestCase


actual = {}
expected = {}

subset = {k:v for k, v in actual.items() if k in expected}
TestCase().assertDictEqual(subset, expected)

NOTE obviously if you are running your test in a method that belongs to a child class that inherits from TestCase (as you almost certainly should be) then it is just self.assertDictEqual(subset, expected)