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?
Here's a bit shorter version which doesn't need try
/ except
and handles the case where the parameters are different type:
def isIn(inside, outside):
if isinstance(inside, dict) and isinstance(outside, dict):
return all(isIn(v, outside.get(k, object())) for k, v in inside.items())
return inside == outside
print(isIn(first, second)) # True
print(isIn(second, first)) # False
print(isIn({}, 9999)) # False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.