『』』
字典排序
字典排序中沒有dictionary.sort()這種排序方法
但是可以通過內建函式sorted()來進行排序,內建函式有返回值
需要重新接收返回值,這種排序是預設通過key排序
.sort這種是物件方法,沒有返回值
『』』
#dictionary.sort()
#這中方法執行報錯,沒有這種方法
dictionary=sorted(dictionary.items())
#dictionary.items() 以列表返回可遍歷的(鍵, 值) 元組陣列
print(dictionary)
#順序排序結果
#[('a', 2), ('c', 3), ('d', 0), ('f', 1)]
#逆序排序結果
dictionary =
dictionary=sorted(dictionary.items(),reverse=true)
print(dictionary)
#逆序排序 結果
#[('f', 1), ('d', 0), ('c', 3), ('a', 2)]
#還可以指定key來指定排序方式
dictionary =
dictionary=sorted(dictionary.items(),key=lambda x:x[1],reverse=true)
print(dictionary)
print() #推導式
#按values排序結果
# [('c', 3), ('a', 2), ('f', 1), ('d', 0)]
list1=[,,,
]#這裡本來就是列表,所以不需要用dict.items轉為列表元組
#這裡對字典列表逆序排序
list1=sorted(list1,key=lambda x:x['salary'],reverse=true)
print(list1)
Python 學習筆記(612) 字典
在python中,字典資料型別的應用非常廣泛。基本知識 定義 字典是可變的無序集合,以鍵值對為基本元素可以儲存各種資料型別。格式 d1 len d1 2鍵 值設定約束 1.鍵的唯一性 a print a 2.鍵的不可變性 字典的基本方法 b a.copy 複製乙個字典生成乙個新的的字典 print ...
Python學習筆記2 字典
除了列表,python中最常用的內建容器就是字典了,這是一種無序的鍵值對形式的物件集合。這其中包含三層含義 無序,即你不應該對字典資料的訪問順序抱有期待,其真是的訪問順序完全由python直譯器決定。鍵值對,這在其它程式語言中也叫做關係陣列或者雜湊,其運用在實際開發中相當普遍,像json或者xml格...
Python2 3字典比較函式
cmp 如果兩個字典的元素相同返回0,如果字典dict1大於字典dict2返回1,如果字典dict1小於字典dict2返回 1。cmp dict1,dict2 比較字典函式是否相等 def get cmp dict src data,dst data if isinstance src data,s...