大佬们遇到过这个问题吗?python怎样对字典排序?求指导!

有一字典{"A":5,"C":4,"B":10,"D":20}怎样最快对这个字典按照value降序排列,变成{“D”:20,"B":10,"A":5,"C":4}?
RISEBY
浏览 245回答 2
2回答

当年话下

dic={"A":5,"C":4,"B":10,"D":20}print(sorted(dic.items(),key=lambdaa:a[1],reverse=True))

一只萌萌小番薯

字典本身是无序的,需要先转成元组再排序如下:a={"A":5,"C":4,"B":10,"D":20}importoperator#按值排序排序b=sorted(a.items(),key=operator.itemgetter(1),reverse=True)print(b)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript