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

前端 未结 16 678
轮回少年
轮回少年 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:08

    In Python 3, you can use dict.items() to get a set-like view of the dict items. You can then use the <= operator to test if one view is a "subset" of the other:

    d1.items() <= d2.items()
    

    In Python 2.7, use the dict.viewitems() to do the same:

    d1.viewitems() <= d2.viewitems()
    

    In Python 2.6 and below you will need a different solution, such as using all():

    all(key in d2 and d2[key] == d1[key] for key in d1)
    

提交回复
热议问题