You could have Python do the looping in C code by using a dictionary view; this does a membership test against all values without creating a new list:
if None not in d.values():
(In Python 2, use dict.viewvalues()
to get a dictionary view, as dict.values()
returns a list there).
Demo on Python 3:
>>> d = {'a': None, 'c': None, 'b': '12345'}
>>> None not in d.values()
False
This will loop over the values until a match is found, just like list membership or a proper any()
test, making this an O(N) test. This differs from a dictionary or set membership test, where hashing can be used to give you a fixed cost test on average.
You were not using any()
properly; drop the [...]
brackets:
if any(v is not None for v in d.values()): # Python 2: use d.itervalues() or d.viewvalues()
If your goal is to test for multiple values, and you need to avoid constant looping for each test, consider creating an inverse index instead:
inverse_index = {}
for key, value in d.items():
inverse.setdefault(value, set()).add(key)
This requires the values to be hashable, however. You can now simply test for each value:
if None not in inverse_index:
in O(1) time.