Skip to content Skip to sidebar Skip to footer

How To Check If Dict Is Subset Of Another Complex 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. superset: dct_1 = { 'x': 'x', 'y':

Solution 1:

Here's a way of doing it, is it enough for you use case ?

defis_subset(superset, subset):
    iftype(superset) != type(subset):
        returnFalseifisinstance(subset, dict):
        for key, value in subset.items():
            try:
                ifnot is_subset(superset[key], value):
                    returnFalseexcept KeyError:
                returnFalseelifisinstance(subset, list):
        for sub_e, super_e inzip(subset, superset):
            ifnot is_subset(super_e, sub_e):
                returnFalseelse:
        if superset != subset:
            returnFalsereturnTrue
        

is_subset(dict_1, dict_2)
# True

Solution 2:

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):
   ifnot 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))

Output:

True

Post a Comment for "How To Check If Dict Is Subset Of Another Complex Dict"