- 一般列表用sort()函数,但是字典中没有内嵌的sort()函数,字典需用sorted()函数,具体用法如下:
- 直接使用sorted(),函数将按Ascall码的顺序只返回字典中的key列表(或者是一个value列表):
""" --coding:utf-8 -*- Time:2023/11/27 11:18 Author:静默追光 """ dic={'b':2,'c':1,'d':4,'a':5,'e':3} a=sorted(dic) 输出: ['a', 'b', 'c', 'd', 'e']
dic={'b':2,'c':1,'d':4,'a':5,'e':3} b=sorted(dic.values())#根据值排序 print(b) 输出: [1, 2, 3, 4, 5]
- 我们可以调用字典中的items()函数按key对它进行排序,并返回一个元组列表:
d=sorted(dic.items())#默认根据key按ASCALL码排序 print(d) #结果: [('a', 5), ('b', 2), ('c', 1), ('d', 4), ('e', 3)]
- 按字典的value值进行排序(x[0]代表key键,x[1]代表values值):
e=sorted(dic.items(),key=lambda x:x[0])#x[0]=key,根据key按ASCALL码排序 print(e) #结果: [('a', 5), ('b', 2), ('c', 1), ('d', 4), ('e', 3)]
f=sorted(dic.items(),key=lambda x:x[1])#x[1]=value,默认升序 print(f) #结果: [('c', 1), ('b', 2), ('e', 3), ('d', 4), ('a', 5)]
g=sorted(dic.items(),key=lambda x:-x[1])#x[0]=key,加'-'为反向排序 print(g) #结果: [('a', 5), ('d', 4), ('e', 3), ('b', 2), ('c', 1)] h=sorted(dic.items(),key=lambda x:x[0],reverse=True)#x[0]=key,reverse=True:反向排序,默认为FALSE print(h) #结果: [('e', 3), ('d', 4), ('c', 1), ('b', 2), ('a', 5)]
- counter是一个dict子类,它是无序集合,其中的元素作为字典的key储存,它们的计数作为字典的value存储。创建counter时,使用以下代码:
from collections import Counter dic_counter=Counter(dic(zip(letters,numbers)))
dic_counter=Counter({'b':2,'c':1,'d':4,'a':5,'e':3}) print(dic_counter) #输出 Counter({'a': 5, 'd': 4, 'e': 3, 'b': 2, 'c': 1})
- 当我们想要按value对字典进行排序时,我们可以使用most_common()函数:
eh=dic_counter.most_common() print(eh) #输出 [('a', 5), ('d', 4), ('e', 3), ('b', 2), ('c', 1)]
- 直接使用sorted(),函数将按Ascall码的顺序只返回字典中的key列表(或者是一个value列表):
在Python中字典排序
最新推荐文章于 2024-05-21 22:46:29 发布