Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find non-Empty value in dict

I have a dict like this:

d = {'first':'', 'second':'', 'third':'value', 'fourth':''}

and I want to find first non-empty value (and it's name, in this example 'third'). There may be more than one non-empty value, but I only want the first one I find.

How can I do this?

like image 965
WiGeeky Avatar asked Dec 04 '25 08:12

WiGeeky


1 Answers

You could use next (dictionaries are unordered - this somewhat changed in Python 3.6 but that's only an implementation detail currently) to get one "not-empty" key-value pair:

>>> next((k, v) for k, v in d.items() if v)
('third', 'value')
like image 73
MSeifert Avatar answered Dec 07 '25 00:12

MSeifert