如何检查dict是否是另一个复杂dict的子集 [英] How to check if dict is subset of another complex dict

查看:78
本文介绍了如何检查dict是否是另一个复杂dict的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要验证另一个dict是否是另一个dict的子集,有一个窍门是在这些dict中有一系列dict.

I need to verify if another dict is a subset of another dict, there is a trick that in these dicts there are array of dict's.

超集:

   dct_1 = {
        'x': 'x',
        'y': [
            {
                't': '123',
                'a': 'a'
            }
        ]
    }

子集:

dict_2 = {
        'x': 'x',
        'y': [
            {
                't': '123'
            }
        ]
    }

来自递归函数检查字典是否是另一本字典的子集答案出现此错误:

TypeError: unhashable type: 'dict'

我的代码:

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


class Test(unittest.TestCase):

    def setUp(self):
        self.dct = {
            'x': 'x',
            'y': [
                {
                    't': '123',
                    'a': 'a'
                }
            ]
        }

    def check_is_subset_true(self, superset, subset):
        return self.assertEqual(is_subset(superset, subset), True)

    def test_is_true(self):
        self.check_is_subset_true(self.dct, {
            'x': 'x',
            'y': [
                {
                    't': '123'
                }
            ]
        })

推荐答案

您可以遍历复杂的词典,并在每个阶段尝试将当前词典与潜在的子集词典进行匹配:

You can traverse the complex dictionary and at each stage, attempt to match the current dictionary with the potential subset dictionary:

def d_eq(d, d1):
   if not isinstance(d, (dict, list)):
      return d == d1
   if isinstance(d, list):
      return all(d_eq(a, b) for a, b in zip(d, d1))
   return all(d.get(i) == d1[i] or d_eq(d.get(i), d1[i]) for i in d1)

def is_sub(d, d1):
  if isinstance(d, list):
     return any(is_sub(i, d1) for i in d)
  return d_eq(d, d1) or (isinstance(d, dict) and any(is_sub(b, d1) for b in d.values()))

print(is_sub(dct_1, dict_2))

输出:

True

这篇关于如何检查dict是否是另一个复杂dict的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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