Python - check if dict value is not None (without iterators)

I wonder if it is possible to get the same result as in this code:

d = {'a':None,'b':'12345','c':None} nones=False for k,v in d.items(): if d[k] is None: nones=True 

or

 any([v==None for v in d.values()]) 

but without a loop iterator or generator?

+6
source share
2 answers

you can use

 nones = not all(d.values()) 

If all values ​​are equal to none, then non will be assigned the value False, otherwise True. This is just an abstraction, although inside it should iterate over the list of values.

+7
source

You could make a Python loop in C code using a dictionary view ; this checks membership on all values ​​without creating a new list:

 if None not in d.viewvalues(): 

In Python 3, dict.values() also returns a dictionary.

Python 2 demo:

 >>> d = {'a': None, 'c': None, 'b': '12345'} >>> None not in d.viewvalues() False 

This will loop over the values ​​until a match is found, just like list membership or the correct any() test, which makes this O (N) test. This is different from a dictionary or an established membership test, where hashing can be used to give you an average fixed cost test.

You did not use any() correctly; omit the brackets [...] :

 if any(v is not None for v in d.itervalues()): # Python 3: use d.values() 

If your goal is to check certain values ​​and you need to avoid a constant loop for each test, consider creating an inverse index:

 inverse_index = {} for key, value in d.items(): inverse.setdefault(value, set()).add(key) 

This requires the values ​​to be hashed. Now you can simply check for each value:

 if None not in inverse_index: 

in O (1) time.

+5
source

All Articles