python字典排序总结
Posted songdanlee
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python字典排序总结相关的知识,希望对你有一定的参考价值。
dic = "abc":18,"adc":19,"abe":20 # 默认对键排序,从小到大,返回排序后键组成的列表 zidian = sorted(dic)#[‘abc‘, ‘abe‘, ‘adc‘] print(zidian) # 对键进行反向(从大到小)排序 zidian = sorted(dic,reverse=True)#[‘adc‘, ‘abe‘, ‘abc‘] print(zidian) # 拿到所有的key,然后再对key排序 zidian = sorted(dic.keys(),reverse=True)#[‘adc‘, ‘abe‘, ‘abc‘] print(zidian) # 对值排序,从小到大 print(dic) zidian = sorted(dic.values())#[18, 19, 20] print(zidian) # 对值排序,从大到小 zidian = sorted(dic.values(),reverse=True)#[20, 19, 18] print(zidian) #可以用dict1.items(),得到包含键,值的元组, # 由于迭代对象是元组,返回值自然是元组组成的列表,x指元组,x[1]是值,x[0]是键 # 键由小到大排序 zidian = sorted(dic.items(),key=lambda x:x[0]) print(zidian) # 键由大到小排序 zidian = sorted(dic.items(),key=lambda x:x[0],reverse=True) print(zidian) # 值由小到大排序 zidian = sorted(dic.items(),key=lambda x:x[1]) print(zidian) # 值由大到小排序 zidian = sorted(dic.items(),key=lambda x:x[1],reverse=True) print(zidian) #itemgetter(0),获取key # itemgetter(1),获取value from operator import itemgetter d = "a":8,"b":4,"c":12,"a":10,"b":1,"e":10 # 键由大到小 print(sorted(d.items(),key=itemgetter(0),reverse=True))#[(‘e‘, 10), (‘c‘, 12), (‘b‘, 1), (‘a‘, 10)] # 值由大到小 print(sorted(d.items(),key=itemgetter(1),reverse=True))#[(‘c‘, 12), (‘a‘, 10), (‘e‘, 10), (‘b‘, 1)]
以上是关于python字典排序总结的主要内容,如果未能解决你的问题,请参考以下文章