I need to know if a dict is included into an other one, recursively, in Python 3:
first = {"one":"un", "two":"deux", "three":"trois" , "sub": { "s1": "sone" }}
second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar", "sub": { "s1": "sone", "s2": "stwo"}}
Usage of dictionary views like described in Test if dict contained in dict is a very nice way, but does not handle recursion case.
I came up with this function:
def isIn(inside, outside):
for k, v in inside.items():
try:
if isinstance(v,dict):
if not isIn(v, outside[k]):
return False
else:
if v != outside[k]:
return False
except KeyError:
return False
return True
Which work:
>>> first.items() <= second.items()
False
>>> isIn(first, second)
True
Is there a better (more Pythonic) way?