簡體   English   中英

如何遍歷按值排序的 Python 字典?

[英]How do I iterate over a Python dictionary, ordered by values?

我有一本像這樣的字典:

{ 'a': 6, 'b': 1, 'c': 2 }

我想通過 value而不是 key 來迭代它。 換句話說:

(b, 1)
(c, 2)
(a, 6)

最直接的方法是什么?

sorted(dictionary.items(), key=lambda x: x[1])

對於你們這些討厭 lambda 的人:-)

import operator
sorted(dictionary.items(), key=operator.itemgetter(1))

但是operator版本需要 CPython 2.5+

對於非 Python 3 程序,您將希望使用 iteritems 來提高生成器的性能,生成器一次生成一個值,而不是一次返回所有值。

sorted(d.iteritems(), key=lambda x: x[1])

For even larger dictionaries, we can go a step further and have the key function be in C instead of Python as it is right now with the lambda.

import operator
sorted(d.iteritems(), key=operator.itemgetter(1))

萬歲!

使用namedtuple通常非常方便。 例如,您有一個包含名稱和分數的字典,並且想要按“分數”排序:

import collections
Player = collections.namedtuple('Player', 'score name')
d = {'John':5, 'Alex':10, 'Richard': 7}

首先以最低分排序:

worst = sorted(Player(v,k) for (k,v) in d.items())

首先以最高分排序:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

'key' 和 'value' 在列出的元組中的順序是 (value, key),但是現在你可以得到名字和分數,比如說第二好的玩家 (index=1) 非常 Python 像這樣:

    player = best[1]
    player.name
        'Richard'
    player.score
         7

items方法為您提供 (key,value) 元組的列表,可以使用sorted和自定義排序鍵對其進行排序:

Python 2.5.1 (r251:54863, Jan 13 2009, 10:26:13) 

>>> a={ 'a': 6, 'b': 1, 'c': 2 }
>>> sorted(a.items(), key=lambda (key,value): value)
[('b', 1), ('c', 2), ('a', 6)]

在 Python 3 中,必須將 lambda 表達式更改為lambda x: x[1]

暫無
暫無

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

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