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

前端 未结 16 656
轮回少年
轮回少年 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条回答
  •  既然无缘
    2020-12-04 10:07

    A short recursive implementation that works for nested dictionaries:

    def compare_dicts(a,b):
        if not a: return True
        if isinstance(a, dict):
            key, val = a.popitem()
            return isinstance(b, dict) and key in b and compare_dicts(val, b.pop(key)) and compare_dicts(a, b)
        return a == b
    

    This will consume the a and b dicts. If anyone knows of a good way to avoid that without resorting to partially iterative solutions as in other answers, please tell me. I would need a way to split a dict into head and tail based on a key.

    This code is more usefull as a programming exercise, and probably is a lot slower than other solutions in here that mix recursion and iteration. @Nutcracker's solution is pretty good for nested dictionaries.

提交回复
热议问题