python中,我们可以对列表、字符串、元祖中的元素进行排序,那对于字典中的元素可以排序吗?其实对于字典本身我们无法进行排序,但是我们可以对字典按值排序。本文介绍python中对字典按照value进行排序的三种方法。

方法一:key使用lambda匿名函数取value进行排序

dict= {'a':1,'b':4,'c':2}
sorted(dict.items(),key = lambda x:x[1],reverse = true)

方法二:使用operator的itemgetter进行排序

test_data_6=sorted(dict_data.items(),key=operator.itemgetter(1))
test_data_7=sorted(dict_data.items(),key=operator.itemgetter(1),reverse=true)
print(test_data_6) #[(8, 2), (10, 5), (7, 6), (6, 9), (3, 11)]
print(test_data_7) #[(3, 11), (6, 9), (7, 6), (10, 5), (8, 2)]

方法三:key和value分装成元祖,再进行排序

f = zip(d.keys(), d.values())
c = sorted(f)
print(c)

字典按value排序内容扩展:

保存为字典后,按字典的value值大小排序,这个才是本题的难点,由于dict是无序的,所以只能用list去排序,把dict的key和value保存为tuplue对象

# 对字典按value排序
a = sorted(d.items(), key=lambda x: x[1], reverse=true)
print(a)

参考代码:

# coding:utf-8

# 作者:上海-悠悠
a = ["a", "b", "a", "c", "a", "c", "b", "d", "e", "c", "a", "c"]

# set集合去重
duixiang = set(a) # 先去重,取出计数对象

# 保存为dict,一一对应
d = {}
for i in duixiang:
  d[i] = a.count(i)


# 对字典按value排序
a = sorted(d.items(), key=lambda x: x[1], reverse=true)
print(a)

到此这篇关于python字典按照value排序方法的文章就介绍到这了,更多相关python中字典如何按照value排序内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!