python3字典的排序问题
参考博客链接 :https://blog.csdn.net/ustbbsy/article/details/796
字典有两个参数,key, value,下面所描述,键:key,值:value , 键值对: items
创建一个字典
dic={'a':26,'g':20,'e':20,'c':24}
1.字典的取值
dic = {'a':26,'g':20,'e':20,'c':24} print(dic.keys()) print(dic.values()) print(dic.items()) # dict_keys(['a', 'g', 'e', 'c']) # dict_values([26, 20, 20, 24]) # dict_items([('a', 26), ('g', 20), ('e', 20), ('c', 24)])
-
可以看出,dic.items() 返回的结果是元组组成的列表
-
也就是说,通过dict1.items()这个函数,把字典形式的键、值,存在了一个元组内。
2.1 sorted
dic = {'a':26,'g':20,'e':20,'c':24} new_dic = sorted(dic) print(new_dic) # ['a','c','e','g']
-
可得出 sorted()默认是对字典的键从小到大进行排序
2.2 对键反向排序
#方式一 dic = {'a':26,'g':20,'e':20,'c':24} new_dic = sorted(dic,reverse=True) print(new_dic) #方式二:我们也可以先拿到所有的key,然后再对key排序 dic = {'a':26,'g':20,'e':20,'c':24} new_dic = sorted(dic.keys(),reverse=True) print(new_dic) #['g','e','c','a']
2.3对值排序
dic = {'a':26,'g':20,'e':20,'c':24} new_dic = sorted(dic.values()) print(new_dic) # [20,20,24,26]
2.4 lambda表达式
g = lambda x:x+1 print(g(1)) #2 print(g(3)) #4 当然,你也可以这样使用: lambda x:x+1(1) 上例的代码x为入口参数,x+1为函数体,用函数来表示为: def g(x): return x+1
2.5另一种方式的排序
dic = {'a':26,'g':20,'e':20,'c':24} print(dic.items()) # dict_items([('a', 26), ('g', 20), ('e', 20), ('c', 24)]) new_dic = sorted(dic.items(),key=lambda x:x[1],reverse=True) print(new_dic) # [('a', 26), ('c', 24), ('g', 20), ('e', 20)]
3.itemgetter
from operator import itemgetter d = {"a":8,"b":4,"c":12} print(sorted(d.items(),key=itemgetter(0),reverse=True)) #itemgetter(0),获取key print(sorted(d.items(),key=itemgetter(1),reverse=True)) #itemgetter(1),获取value #结果 # [('c',12),('b',4),('a',8)] # [('c',12),('a',8),('b',4)]