在dict中查找非空值

时间:2017-06-01 09:12:25

标签: python python-3.x dictionary

我有这样的字典:

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

我希望找到第一个非空值(以及它的名称,在本例中为'third')。可能有多个非空值,但我只想要找到第一个。

我该怎么做?

5 个答案:

答案 0 :(得分:5)

使用保留元素顺序的OrderedDict。然后循环遍历它们并找到第一个非空的:

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

答案 1 :(得分:3)

你可以使用next(字典是无序的 - 这在Python 3.6中有所改变,但目前只有一个实现细节)才能得到一个" not-empty"键值对:

>>> next((k, v) for k, v in d.items() if v)
('third', 'value')

答案 2 :(得分:2)

喜欢这个吗?

def none_empty_finder(dict):
    for e in dict:
        if dict[e] != '':
            return [e,dict[e]]

答案 3 :(得分:1)

d = {'first':'', 'second':'', 'third':'value', 'fourth':''}
for k, v in d.items():
    if v!='':
        return k, v

修改1

from the comment如果值为None'',我们最好使用if v:代替if v!=''if v!=''仅检查''并跳过其他人

答案 4 :(得分:0)

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

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