Ioan Kats
Ioan Kats

Reputation: 521

Alternative implementations with ternary operators, one liners

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": "[email protected]",
  "picture": "https://s.gravatar.com/avatar/a.png",
  "updated_at": "2020-05-07T08:44:10.091Z",
  "email": "[email protected]",
  "email_verified": 'false',
  "iss": "x",
  "sub": "x",
  "aud": "x",
  "iat": 1588841051,
  "exp": 1588877051
}

So the most obvious thing is this one :

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

I was wondering which are some better (efficient/faster) ways implementing this. I mean something like one liner [i know that the one liner that i wrote is wrong]

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

Upvotes: 0

Views: 107

Answers (2)

Gábor Fekete
Gábor Fekete

Reputation: 1358

You could also convert the keys of the dictionary into a set and use set difference to get the missing values:

>>> set(obligatory_data_fields)-set(a)
>>> set() # Empty set, every key in obligatory_data_fields is present in 'a'

Upvotes: 0

tzaman
tzaman

Reputation: 47850

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

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

If you actually need the names of each missing field, you can use a list comprehension:

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

Upvotes: 1

Related Questions