[英]Recursively test if dict is contained in dict
I need to know if a dict is included into an other one, recursively, in Python 3:我需要知道在 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. 如果 dict 中包含的 dict 中描述的字典视图的使用是一种非常好的方法,但不处理递归情况。
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?有没有更好(更 Pythonic)的方式?
Here's a bit shorter version which doesn't need try
/ except
and handles the case where the parameters are different type:这是一个较短的版本,不需要
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.