三元运算符和一个内衬的替代实现

Hello i have a dictionary with some data and i would like to check if every field of obligatory_data_fields is included in this dictionary.

obligatory_data_fields = ("nickname", "name", "picture", "updated_at", "email", "email_verified",
                                 "iss", "sub", "aud", "iat", "exp")


a = {
  "nickname": "a",
  "name": "abcd@email.gr",
  "picture": "https://s.gravatar.com/avatar/a.png",
  "updated_at": "2020-05-07T08:44:10.091Z",
  "email": "abcd@email.gr",
  "email_verified": 'false',
  "iss": "x",
  "sub": "x",
  "aud": "x",
  "iat": 1588841051,
  "exp": 1588877051
}

因此,最明显的是这一件事:

for data in obligatory_data_fields:
    if data in a:
        pass
    else:
        print('missing ', data)

我想知道哪种更好(有效/更快)的方法来实现这一目标。 我的意思是像一个班轮一样[我知道我写的那一个班轮是错误的]

e.g pass if data in a else print('missing ', data) for data in obligatory_data_fields

评论
  • 闹心*
    闹心* 回复

    If you just want to validate, you can use all:

    >>> all(field in a for field in obligatory_data_fields)
    True
    

    如果您实际上需要每个缺失字段的名称,则可以使用列表理解:

    >>> missing = [field for field in obligatory_data_fields if field not in a]
    >>> missing
    []