检查字典的递归函数是另一个字典的子集 [英] Recursive function to check dictionary is a subset of another dictionary

查看:61
本文介绍了检查字典的递归函数是另一个字典的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想递归检查一个字典是否是另一个字典的子集.让我们假设两个字典都具有内置类型作为项目.

I'd like to check whether a dictionary is a subset of another dictionary recursively. Let's assume both dictionaries having builtin types as items.

我已经看到已经有一个非常老的线程解决方案,但仍未完全完成,以下功能在几乎所有情况下都可以正常使用,但是如果子集具有超集中不存在的值,则它会惨败,即:

I've seen there is already a very old thread Python: Check if one dictionary is a subset of another larger dictionary trying to solve something similar but not quite... Because none of the answers living there will serve for my purposes I've decided to post my own solution in there but it is still not fully complete, the below function is working ok for almost all cases but it fails miserably in cases when the subset has values that don't exist in the superset, ie:

def is_subset(superset, subset):
    for key, value in superset.items():
        if key not in subset:
            continue

        if isinstance(value, dict):
            if not is_subset(value, subset[key]):
                return False
        elif isinstance(value, str):
            if not subset[key] in value:
                return False
        elif isinstance(value, list):
            if not set(subset[key]) <= set(value):
                return False
        elif isinstance(value, set):
            if not subset[key] <= value:
                return False
        else:
            if not subset[key] == value:
                return False

    return True

superset = {'question': 'mcve', 'metadata': {}}
subset = {'question': 'mcve', 'metadata': {'author': 'BPL'}}

print(is_subset(superset, subset))

该函数返回True,但应返回False.那么,您将如何解决呢?

The function returns True but it should return False. So, how would you fix it?

推荐答案

您的代码逻辑是颠倒的.请注意如何将每个元素放在超集中,如果它们不在子集中中,则继续.您要做的是将子集中中的每个元素都包含在内,并检查它们是否在超集中.

Your code logic is upside down. Notice how you take each element in the superset and continue if they are not in the subset. What you want to do is take each element in the subset and check that they are in the superset.

这是您的代码的固定版本.

Here is a fixed version of you code.

def is_subset(superset, subset):
    for key, value in subset.items():
        if key not in superset:
            return False

        if isinstance(value, dict):
            if not is_subset(superset[key], value):
                return False

        elif isinstance(value, str):
            if value not in superset[key]:
                return False

        elif isinstance(value, list):
            if not set(value) <= set(superset[key]):
                return False
        elif isinstance(value, set):
            if not value <= superset[key]:
                return False

        else:
            if not value == superset[key]:
                return False

    return True

以下是该函数给出正确结果的一些示例.

Here are some example of the function giving the correct result.

superset = {'question': 'mcve', 'metadata': {}}
subset = {'question': 'mcve', 'metadata': {'author': 'BPL'}}

is_subset(superset, subset) # False

superset = {'question': 'mcve', 'metadata': {'foo': {'bar': 'baz'}}}
subset = {'metadata': {'foo': {}}}

is_subset(superset, subset) # True

superset = {'question': 'mcve', 'metadata': {'foo': 'bar'}}
subset = {'question': 'mcve', 'metadata': {}, 'baz': 'spam'}

is_subset(superset, subset) # False

这篇关于检查字典的递归函数是另一个字典的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆