【发布时间】:2016-05-03 13:22:48
【问题描述】:
我需要知道一个 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)的方法?
【问题讨论】:
-
如果第一个参数为空,则任何第二个参数都将通过测试。例如:
isIn({}, 9999) == True.
标签: python dictionary recursion