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()):
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.
source share