对字典值进行排序并丢弃那些没有值的字典值

时间:2013-06-11 09:13:28

标签: python dictionary

我有以下函数,它接受一个字典,对它进行排序并返回字典值列表。

def sort_dict_values(dic):
keys = dic.keys()
keys.sort()
return map(dic.get, keys)

dict1 = {"b":"1", "a":"2", "d":"", "c":"3"}
sorted_list = sort_dict_values(dict1)

此函数返回包含空值项的列表。例如结果列表将是:

["2","1","3",""]

我想丢弃没有价值的物品。例如丢弃“d”,因为它是空的。结果列表应如下所示:

["2","1","3"]

4 个答案:

答案 0 :(得分:4)

>>> dict1 = {"b":"1", "a":"2", "d":"", "c":"3"}
>>> [v for k, v in sorted(dict1.items()) if v]
['2', '1', '3']

正如@AlexChamberlain在评论中所说,通过首先执行O(N)过滤器,它将减少O(N log N)排序算法的负荷

>>> [v for k, v in sorted(x for x in dict1.items() if x[1])]
['2', '1', '3']

答案 1 :(得分:2)

您可以在此处使用filter

from itertools import imap
def sort_dict_values(dic):
    keys = dic.keys()
    keys.sort()
    return filter(None,imap(dic.get, keys))

dict1 = {"b":"1", "a":"2", "d":"", "c":"3"}
print sort_dict_values(dict1)   
#['2', '1', '3']

或者如@Alex Chamberlain所建议的那样,在排序之前过滤键会更好,因为这会减少要排序的项目数量:

def sort_dict_values(dic):
    keys = sorted(k for k,v in dic.iteritems() if v !='')
    return map(dic.get, keys)

dict1 = {"b":"1", "a":"2", "d":"", "c":"3"}
print sort_dict_values(dict1) 
#['2', '1', '3']

答案 2 :(得分:0)

只需过滤排序结果

>>> a = ["2","1","3",""]
>>> filter(None, a)
['2', '1', '3']

答案 3 :(得分:0)

一个班轮:

[v for k,v in sorted(zip(d.keys(),d.values())) if v]