當前位置:首頁 » 編程語言 » python3對字典排序

python3對字典排序

發布時間: 2022-06-12 05:42:31

python3.0中sorted函數怎麼用

【Python】 sorted函數
我們需要對List、Dict進行排序,Python提供了兩個方法
對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變

--------------------------------sorted---------------------------------------
>>> help(sorted)
Help on built-in function sorted in mole __builtin__:

sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
---------------------------------sort----------------------------------------
>>> help(list.sort)
Help on method_descriptor:

sort(...)
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
-----------------------------------------------------------------------------

iterable:是可迭代類型;
cmp:用於比較的函數,比較什麼由key決定;
key:用列表元素的某個屬性或函數進行作為關鍵字,有默認值,迭代集合中的一項;
reverse:排序規則. reverse = True 降序 或者 reverse = False 升序,有默認值。
返回值:是一個經過排序的可迭代類型,與iterable一樣。

參數說明:
(1) cmp參數
cmp接受一個函數,拿整形舉例,形式為:
def f(a,b):
return a-b
如果排序的元素是其他類型的,如果a邏輯小於b,函數返回負數;a邏輯等於b,函數返回0;a邏輯大於b,函數返回正數就行了

(2) key參數
key也是接受一個函數,不同的是,這個函數只接受一個元素,形式如下
def f(a):
return len(a)
key接受的函數返回值,表示此元素的權值,sort將按照權值大小進行排序

(3) reverse參數
接受False 或者True 表示是否逆序

例子:
(1)按照元素長度排序
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
def f(x):
return len(x)
sort(key=f)
print L

輸出:
[{1: 9}, {1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}]

(2)按照每個字典元素裡面key為1的元素的值排序
L = [{1:5,3:4},{1:3,6:3},{1:1,2:4,5:6},{1:9}]
def f2(a,b):
return a[1]-b[1]
L.sort(cmp=f2)
print L
. 對由tuple組成的List排序
Python代碼
>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]

用key函數排序:返回由tuple組成的list
Python代碼
>>> sorted(students, key=lambda student : student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

用cmp函數排序
Python代碼
>>> sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

用 operator 函數來加快速度,
Python代碼
>>> from operator import itemgetter, attrgetter
>>> sorted(students, key=itemgetter(2))

用 operator 函數進行多級排序
Python代碼
>>> sorted(students, key=itemgetter(1,2)) # sort by grade then by age
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]

2. 對由字典排序 ,返回由tuple組成的List,不再是字典。
Python代碼
>>> d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
>>> sorted(d.iteritems(), key=itemgetter(1), reverse=True)
[('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]

㈡ python 字典排序 字典序排序是什麼意思

字典就是包含key:value對的集合
比如
L = [{"name": "zhangsan", "birth":19920208, "gender":"m"}, {"name": "lisi", "birth":19900609, "gender":"m"}, {"name": "wanghong", "birth":19950907, "gender":"f"}]
對字典排序就是對列表進行排序後列印:
from operator import itemgetter

L = sorted(L,key=itemgetter('birth'),reverse=True)

for i in range(0,len(L)):

... print("Name: {:10} Gender: {:2} Birth: {}".format(L[i]["name"],L[i]["gender"],L[i]["birth"]))

㈢ Python字典嵌套字典排序,該怎麼處理

感覺這個需求有些許問題,因為通常對比排序的都是同一類型的數據,譬如aaa代表是年齡,bbb代表的是工資,等等... 所以不會拿自己的年齡和工資作一次排序。

# 要做的話,可以手動給它並成一個新列『sort_key』。 obj就是你最外層的a,免得同名混淆

for i in obj:

obj[i]['sort_key'] = obj[i].values()[0]

# 目的是構造出這樣的結構:

# ('c', {'sort_key': 1, 'ccc': 1}), ('d', {'sort_key': 2, 'ddd': 2}), .....)

print(sorted(obj.items(), key = lambda x:x[1]['sort_key']))

㈣ python字典怎麼排序

python字典怎麼排序?
定義一個字典類型
mydict = {2: '小路', 3: '黎明', 1: '郭富城', 4:'周董'}
可分別列印 key和value 看一下數據
按KEY排序,使用了 lambda和 reverse= False(正序)
key和value都輸出
reverse= True(逆序)
按value排序,漢字次序不是按拼音輸出
sorted並不改變字典本身的數據次序。
輸出後為列表和元組
可以 A = sorted(mydict.items(),key = lambda mydict:mydict[1],reverse= False) 賦值給A ,A的次序是變化後的
推薦:《Python教程》
注意事項
sorted並不改變字典本身的數據次序
如果要變化後的 可以賦值給另一個列表變數以上就是小編分享的關於python字典怎麼排序的詳細內容希望對大家有所幫助,更多有關python教程請關注環球青藤其它相關文章!

㈤ python 字典排序

字典是無序的,兄弟

你看嘛:

>>>testmap={123:['aaa',5],234:['bbb',2],345:['ccc',3],456:['ddd',1]}
>>>printtestmap
{456:['ddd',1],345:['ccc',3],234:['bbb',2],123:['aaa',5]}
>>>testmap={456:['ddd',1],234:['bbb',2],345:['ccc',3],123:['aaa',5]}
>>>printtestmap
{456:['ddd',1],345:['ccc',3],234:['bbb',2],123:['aaa',5]}
>>>

㈥ python中字典能排序嗎

用標準的dict生成的字典是無序的。但python在標准庫中提供了ordereddict,它提供了有序字典的數據結構。

㈦ python怎麼對字典進行排序

python 字典(dict)的特點就是無序的,按照鍵(key)來提取相應值(value),如果我們需要字典按值排序的話,那可以用下面的方法來進行:

1 下面的是按照value的值從大到小的順序來排序。

dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[1], reverse = True)
print dict

輸出的結果:
[('aa', 74), ('a', 31), ('bc', 5), ('asd', 4), ('c', 3), ('d', 0)]

下面我們分解下代碼
print dic.iteritems() 得到[(鍵,值)]的列表。
然後用sorted方法,通過key這個參數,指定排序是按照value,也就是第一個元素d[1的值來排序。reverse = True表示是需要翻轉的,默認是從小到大,翻轉的話,那就是從大到小。

2 對字典按鍵(key)排序:
dic = {'a':31, 'bc':5, 'c':3, 'asd':4, 'aa':74, 'd':0}
dict= sorted(dic.iteritems(), key=lambda d:d[0]) d[0]表示字典的鍵
print dict

㈧ Python字典排序問題

python3.7以上默認是按照你添加字典項目的順序,而不會給你排序

python3.6以下連插入順序都是不保證的

熱點內容
我的世界搭建無正版驗證伺服器 發布:2024-05-05 17:03:48 瀏覽:817
我的世界伺服器地址寶可夢 發布:2024-05-05 17:00:16 瀏覽:254
dede企業源碼 發布:2024-05-05 16:57:53 瀏覽:786
如何查看java版本 發布:2024-05-05 16:45:05 瀏覽:494
轉子繞組電動機控制櫃如何配置 發布:2024-05-05 16:45:04 瀏覽:917
搭建游戲要多大伺服器 發布:2024-05-05 16:44:16 瀏覽:346
雲伺服器ecs網站 發布:2024-05-05 16:35:55 瀏覽:563
c語言列印正方形 發布:2024-05-05 16:09:20 瀏覽:643
編程用箭頭 發布:2024-05-05 15:54:21 瀏覽:794
步驟條源碼 發布:2024-05-05 15:35:55 瀏覽:846