0

I am looking for a way to check if a dict is contained in another:

big = {"result": {"code": "1000", "msg" : "oh yeah"} }
small = {"result": {"code": "1000"}}

test(small, big) # should be True ( small <= big )

Since the key/pair of "result" is another dict, the previous answers in stackoverflow bellow FAIL, and do not solve the problem (they work only on simpler dicts). Also, the value could be a list. I want the answer in a general JSON model.

Python: Check if one dictionary is a subset of another larger dictionary

Test if dict contained in dict

Vanquished Wombat
  • 9,075
  • 5
  • 28
  • 67
aod
  • 155
  • 1
  • 5

1 Answers1

0

Since you seem to be defining "contained in" recursively - i.e. A dict is contained in another if every key in the smaller dict exists in the larger and their either have the same value or the value of the smaller is "contained in" the larger - recursion is an obvious choice for solving the problem.

Try something like this:

def is_subset(small, large):
    if isinstance(small, dict) and isinstance(large, dict):
        for key in small.keys():
            if not key in large:
                return False
            elif not is_subset(small[key], large[key]):
                return False
        return True
    elif isinstance(small, list) and isinstance(large, list):
        for s_item in small:
            if not any(is_subset(s_item, l_item) for l_item in large):
                return False
        return True
    else:
        return small == large
David Scarlett
  • 3,171
  • 2
  • 12
  • 28