您可以使用字典视图:
# Python 2if first.viewitems() <= second.viewitems(): # true only if `first` is a subset of `second`# Python 3if first.items() <= second.items(): # true only if `first` is a subset of `second`
字典视图是Python 3中的标准,在Python
2中,您需要在标准方法前加上
view。它们的作用类似于集合,并
<=测试其中一个是否是另一个的子集(或等于另一个)的子集。
Python 3演示:
>>> first = {"one":"un", "two":"deux", "three":"trois"}>>> second = {"one":"un", "two":"deux", "three":"trois", "foo":"bar"}>>> first.items() <= second.items()True>>> first['four'] = 'quatre'>>> first.items() <= second.items()False这也适用于 不可散列的值 ,因为键已经使键值对唯一。关于这一点,文档有点令人困惑,但是即使使用可变值(例如,列表),该方法也可以工作:
>>> first_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei']}>>> second_mutable = {'one': ['un', 'een', 'einz'], 'two': ['deux', 'twee', 'zwei'], 'three': ['trois', 'drie', 'drei']}>>> first_mutable.items() <= second_mutable.items()True>>> first_mutable['one'].append('ichi')>>> first_mutable.items() <= second_mutable.items()False您还可以将
all()函数与生成器表达式一起使用;使用
object()定为定点检测简明缺失值:
sentinel = object()if all(first[key] == second.get(key, sentinel) for key in first): # true only if `first` is a subset of `second`
但这不像使用字典视图那样可读性和表达力强。



