检查字典是否有多个键

rvi*_*hne 0 python dictionary key python-3.x

如何检查字典(实际上是字典对象)是否具有所有给定的密钥集(复数)?

到目前为止,我使用过:

d = { 'a': 1, 'b': 2, 'c': 3 }
keys = ('a', 'b')

def has_keys(d, keys):
    for key in keys:
        if not key in d:
            return False
    return True
Run Code Online (Sandbox Code Playgroud)

这样做有更优雅和Pythonic的方式吗?

Suk*_*lra 11

使用内置功能 all()

>>> d = { 'a': 1, 'b': 2, 'c': 3 }
>>> keys = ('a', 'b')
>>> all(elem in d for elem in keys)
True
>>> keys = ('a', 'b', 'd')
>>> all(elem in d for elem in keys)
False
Run Code Online (Sandbox Code Playgroud)

  • 那是一个生成器表达式.它会在请求时生成元素并且"全部"短路,并在知道后立即返回值. (3认同)