我需要知道dict是否在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"}}
使用Test if dict contained in dict中描述的字典视图是一种非常好的方法,但不处理递归情况。
我想出了这个功能:
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
哪项工作:
>>> first.items() <= second.items()
False
>>> isIn(first, second)
True
但是有更好的(更加pythonic)方式吗?
答案 0 :(得分:1)
这是一个较短的版本,它不需要try
/ except
并处理参数类型不同的情况:
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