How to use comprehension to find dict key when value is "None"?

Viewed 94

How to use comprehension to find dict key when value is None? Is there a one liner instead of the following code?

def Func():
    for k, v in some_dict.items()
        if not v:
            return k
2 Answers
result = next((k for k, v in some_dict.items() if not v), None)

This uses next to iterate over the generator and return the first k whose v is falsey, or None if no item matches that condition. If you prefer to raise an exception when no item matches, leave out the None default value.

Try this (note empty lists will be None, and big lists default gets first element):

l=next((k for k, v in some_dict.items() if not v),None)
print(l)

Or:

l=next((k for k in some_dict.keys() if not some_dict[k]),None)
print(l)
Related