我有一個從資料庫的兩個欄位中讀取的值的字典:字串欄位和數字欄位,字串欄位是唯一的,因此這是字典的鍵,
我可以對鍵進行排序,但是如何根據值進行排序?
注意:我在這里閱讀了堆疊溢位問題,可能會更改我的代碼以包含字典串列,但是由于我實際上并不需要字典串列,因此我想知道是否有更簡單的解決方案來按升序或降序進行排序,
解決方案:
Python 3.7+或CPython 3.6
字典保留Python 3.7+中的插入順序,在CPython 3.6中相同,
>>> x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
>>> {k: v for k, v in sorted(x.items(), key=lambda item: item[1])}
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
或者
>>> dict(sorted(x.items(), key=lambda item: item[1]))
{0: 0, 2: 1, 1: 2, 4: 3, 3: 4}
較舊的Python
無法對字典進行排序,只能獲得已排序字典的表示形式,字典本質上是無序的,但其他型別(例如串列和元組)不是,因此,您需要一種有序的資料型別來表示排序后的值,這將是一個串列-可能是一個元組串列,
例如,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x將是按每個元組中第二個元素排序的元組串列,dict(sorted_x) == x,
對于那些希望對鍵而不是值進行排序的人:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
在Python3中我們可以使用
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=lambda kv: kv[1])
如果要將輸出作為字典,則可以使用collections.OrderedDict:
import collections
sorted_dict = collections.OrderedDict(sorted_x)
本文首發于python黑洞網,博客園同步跟新
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/275667.html
標籤:Python
上一篇:3、操作串列
