簡體   English   中英

按優先級排序Python字典

[英]Sorting a Python Dictionary by Priority

我有一個python字典,由(名稱,值)對組成

pyDictionary = {"Bob":12,"Mellissa":12,"roger":13}

我想要做的是獲得上面字典的排序版本,其中排序是通過給出值的第一優先級來完成的,如果兩對的值相同則應該通過詞典比較名稱進行比較。

我怎么能在python3.7中實現這一點?

您可以使用key sorted ,並從結果中構建OrderedDict以保持順序。

(最后一步只需要python 3.6 < ,在Python 3.7中,dicts按其密鑰插入時間排序)


from collections import OrderedDict
d = {"Mellissa":12, "roger":13, "Bob":12}

OrderedDict(sorted(d.items(), key=lambda x: (x[1], x[0])))
# dict(sorted(d.items(), key=lambda x: (x[1], x[0]))) # for Python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]

或者您也可以使用operator.itemgetter直接從每個元組中獲取valuekey

OrderedDict(sorted(d.items(), key=itemgetter(1,0)))
# dict(sorted(d.items(), key=itemgetter(1,0))) # python 3.7
# [('Bob', 12), ('Mellissa', 12), ('roger', 13)]

您可以使用鍵函數對dict項進行排序,該函數可以反轉鍵值元組的順序:

dict(sorted(pyDictionary.items(), key=lambda t: t[::-1]))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM