Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I using `all` correctly?

Tags:

python

A user asked (Keyerror while using pandas in PYTHON 2.7) why he was having a KeyError while looking in a dictionary and how he could avoid this exception.

As an answer, I suggested him to check for the keys in the dictionary before. So, if he needed all the keys ['key_a', 'key_b', 'key_c'] in the dictionary, he could test it with:

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

This way he could ignore dictionaries that didn't have the expected keys (the list of dictionaries is created out of JSON formatted lines loaded from a file). *Refer to the original question for more details, if relevant to this question.

A user more experienced in Python and SO, which I would consider an authority on the matter for its career and gold badges told me I was using all incorrectly. I was wondering if this is really the case (for what I can tell, that works as expected) and why, or if there is a better way to check if a couple of keys are all in a dictionary.

like image 407
Peque Avatar asked Jun 11 '15 14:06

Peque


1 Answers

Yes that will work fine, but you don't even need the list comprehension

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

If you have the surrounding [], it will evaluate all the elements before calling all. If you remove them, the inner expression is a generator, and will short-circuit upon the first False.

like image 62
Cory Kramer Avatar answered Oct 01 '22 07:10

Cory Kramer