0

I have a method that accepts a dict as an input and does some formatting on the dict.

I would like to ensure the dict contains the required entries before starting the formatting. At the moment I have the code

if not ('email' in payload and
        'renewal_date' in payload and
        'username' in payload
        ):
    raise InvalidDictContentsError

Some of the dicts will have 15 or so items in it so it gets very long. Is there a more elegant way of verifying the dict?

martineau
  • 112,593
  • 23
  • 157
  • 280
user7692855
  • 1,327
  • 2
  • 14
  • 34
  • Yes, you can use `set` methods to test a bunch of keys at once. – PM 2Ring Nov 19 '17 at 15:02
  • @ABDULNIYASPM Sure that works (I assume that the `I` is a typo and you meant `l`). But a `dict.keys()` View object is set-like and you can use subset or superset testing on it, which is faster than testing items one by one, especially if you're testing against a fixed set like `{'email', 'renewal_date', 'username'}` – PM 2Ring Nov 19 '17 at 15:08

0 Answers0