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)]
原文地址:https://www.cnblogs.com/songdanlee/p/11135282.html
时间: 2024-10-31 11:46:10