Am I using everything correctly?

The user asked ( Keyerror when using pandas in PYTHON 2.7 ) why he had KeyError when viewed in the dictionary and how he could avoid this exception.

As an answer, I suggested that he check the keys in the dictionary earlier. So, if he needs all the keys ['key_a', 'key_b', 'key_c'] in the dictionary , he can check it with:

 if not all([x in dictionary for x in ['key_a', 'key_b', 'key_c']]): continue 

Thus, he could ignore dictionaries that did not have the expected keys (a list of dictionaries was created from formatted JSON strings loaded from a file). * Refer to the original question for more details if this relates to this issue.

A user who is more experienced in Python and SO, who I consider to be an authority on this issue for my career and gold badges, told me that I misused all . I was wondering if this is true (for what I can say, it works as expected) and why, or if there is a better way to check if there are several keys in the dictionary.

+5
source share
1 answer

Yes, it will work fine, but you don’t even need to understand the list

 if not all(x in dictionary for x in ['key_a', 'key_b', 'key_c']): continue 

If you have an surrounding [] , it will evaluate all elements before calling all . If you delete them, the internal expression will be a generator and will be short-circuit on the first False .

+13
source

All Articles