Keys in dict and keys not in dict

Chris Angelico rosuav at gmail.com
Sun Mar 18 23:41:05 EDT 2018


On Mon, Mar 19, 2018 at 2:32 PM, Andrew Z <formisc at gmail.com> wrote:
> hello,
>
>  i'd like to check if a function parameter (json) has all the keys I expect
> it to have and if it doesn't - point out the one that is missing.
>
>  What's the good way of doing that?
>
> "good way" - something concise... i'd like to avoid using :
>  if key in json:
>     #pass
>  else
>    print(" Oops, i did it again ...")

Sounds like a set operation to me.

expected = {"foo", "bar", "spam"}
missing = expected - set(json)
if missing:
    print("Missing keys:", missing)

ChrisA



More information about the Python-list mailing list