【问题标题】:Recursively test if dict is contained in dict递归测试dict是否包含在dict中
【发布时间】: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


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多