python - check if any value of dict is not None (without iterators)

后端 未结 2 1158
离开以前
离开以前 2021-02-05 06:39

I wonder if it is possible to gain the same output as from this code:

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


        
相关标签:
2条回答
  • 2021-02-05 07:20

    You can use

    nones = not all(d.values())
    

    If all values are not None, nones would be set to False, else True. It is just an abstraction though, internally it must iterate over values list.

    0 讨论(0)
  • 2021-02-05 07:30

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

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

    Demo on Python 2:

    >>> 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 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.itervalues()):  # Python 3: use d.values()
    

    If your goal is to test for certain 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.

    0 讨论(0)
提交回复
热议问题