導航:首頁 > 編程語言 > pythonlistdict排序

pythonlistdict排序

發布時間:2023-09-08 06:02:44

『壹』 python中字典能排序嗎

字典本身就是無序的,也就不存在排序。

但是可以參照鍵、值,就行排序輸出元組列表,

例如圖中例子

『貳』 python 中dictionary值可以排序嗎

可以按照key或value排序:

測試dict字典內容如下:
test_dict={'zhangsan':20,'lisi':30,'wangerma':40}
1. 按key順序排列
for key in sorted(test_dict.iterkeys()):print "%s: %s" % (key, test_dict[key])

若要按key值降序排列:
for key in sorted(test_dict.iterkeys(),reverse=True):print "%s: %s" % (key, test_dict[key])

2. 按value數序排列
for key, value in sorted(test_dict.iteritems(), key=lambda (k,v): (v,k)):print "%s: %s" % (key, value)

若要按value值降序排列:
for key, value in sorted(test_dict.iteritems(), key=lambda (k,v): (v,k),reverse=True):print "%s: %s" % (key, value)

轉自:http://lovesoo.org/python-dict-sorted-by-key-or-value.html

『叄』 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的字典輸出時候默認排序問題

dict的特點就是存儲的key-value序對是沒有順序的!這和list不一樣,它在內存中存儲是無序的

閱讀全文

與pythonlistdict排序相關的資料

熱點內容
ios如何使用安卓的帳號 瀏覽:873
程序員公園采訪 瀏覽:801
程序員實戰教程要多長時間 瀏覽:964
企業數據加密技巧 瀏覽:125
租雲伺服器開發 瀏覽:804
程序員告白媽媽不同意 瀏覽:327
攻城掠地怎麼查看伺服器 瀏覽:592
android開機黑屏 瀏覽:568
mc純生存伺服器是什麼意思 瀏覽:440
樹莓派火焰蜂鳴器python 瀏覽:898
我的世界伺服器強制疾跑怎麼開 瀏覽:277
用什麼app看施工圖紙 瀏覽:493
張三學python函數 瀏覽:379
女子程序員照片 瀏覽:307
武漢c程序員招聘 瀏覽:684
csk跟蹤演算法 瀏覽:26
數據挖掘中用到的演算法 瀏覽:845
更改ubuntu伺服器地址 瀏覽:504
學做燒菜用什麼app 瀏覽:704
程序框圖怎麼加密 瀏覽:374