关于python:python中字典如何按照value排序

5次阅读

共计 542 个字符,预计需要花费 2 分钟才能阅读完成。

本文教程操作环境:windows7 零碎、Python 3.9.1,DELL G3 电脑。

办法一: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)

以上就是本次分享的全部内容,当初想要学习编程的小伙伴指路微信公众号 -Python 技术大本营,欢送各位的到来哦~

正文完
 0