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

前端 未结 16 663
轮回少年
轮回少年 2020-12-04 09:29

I\'m trying to write a custom filter method that takes an arbitrary number of kwargs and returns a list containing the elements of a database-like list that contain

16条回答
  •  Happy的楠姐
    2020-12-04 10:00

    Most of the answers will not work if within dict there are some arrays of other dicts, here is a solution for this:

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

    Taken from How to check if dict is subset of another complex dict

提交回复
热议问题