简体   繁体   中英

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?

Use an OrderedDict which preserves the order of elements. Then loop over them and find the first that isn't empty:

from collections import OrderedDict
d = OrderedDict()
# fill d
for key, value in d.items():
    if value:
        print(key, " is not empty!")

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 this?

def none_empty_finder(dict):
    for e in dict:
        if dict[e] != '':
            return [e,dict[e]]
d = {'first':'', 'second':'', 'third':'value', 'fourth':''}
for k, v in d.items():
    if v!='':
        return k, v

Edit 1

from the comment if the value is None or '' we better use if v: instead of if v!='' . if v!='' only check the '' and skip others

您可以找到空元素并列出它们:

 non_empty_list = [(k,v) for k,v in a.items() if v]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM