python怎样对字典排序?

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

幕布斯7119047

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

MM们

字典本身是无序的,需要先转成元组再排序如下: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