我有一个从数据库中两个字段读取的值字典:字符串字段和数字字段。字符串字段是唯一的,因此它是字典的关键字。

我可以按关键字排序,但如何根据值排序?

注意:我在这里读过堆栈溢出问题。如何根据字典的值对字典列表进行排序?并且可能会更改我的代码,使其具有字典列表,但由于我确实不需要字典列表,我想知道是否有更简单的解决方案来按升序或降序排序。


当前回答

从Python 3.6开始,dict对象现在按插入顺序排序。这是Python 3.7规范中的正式版本。

>>> words = {"python": 2, "blah": 4, "alice": 3}
>>> dict(sorted(words.items(), key=lambda x: x[1]))
{'python': 2, 'alice': 3, 'blah': 4}

在此之前,您必须使用OrderedDict。

Python 3.7文档说明:

在3.7版中更改:字典顺序保证插入顺序该行为是CPython在3.6中的实现细节。

其他回答

另一个答案中提到的集合解决方案绝对是极好的,因为您在键和值之间保留了一种联系,这在字典中是极其重要的。

我不同意另一个答案中的第一选择,因为它会扔掉钥匙。

我使用了上面提到的解决方案(代码如下所示),并保留了对键和值的访问权,在我的情况下,排序是对值进行的,但重要的是对值排序后的键排序。

from collections import Counter

x = {'hello':1, 'python':5, 'world':3}
c=Counter(x)
print( c.most_common() )


>> [('python', 5), ('world', 3), ('hello', 1)]

这是一个在d.values()和d.keys()上使用zip的解决方案。此链接(在Dictionary视图对象上)下面的几行是:

这允许使用zip()创建(value,key)对:pairs=zip(d.values(),d.keys())。

因此,我们可以执行以下操作:

d = {'key1': 874.7, 'key2': 5, 'key3': 8.1}

d_sorted = sorted(zip(d.values(), d.keys()))

print d_sorted 
# prints: [(5, 'key2'), (8.1, 'key3'), (874.7, 'key1')]

使用Python 3.5

虽然我发现公认的答案很有用,但我也感到惊讶的是,它还没有更新,以引用标准库集合模块中的OrderedDict作为一种可行的现代替代方案-旨在解决这类问题。

from operator import itemgetter
from collections import OrderedDict

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = OrderedDict(sorted(x.items(), key=itemgetter(1)))
# OrderedDict([(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)])

官方OrderedDict文档也提供了一个非常类似的示例,但使用lambda作为排序函数:

# regular unsorted dictionary
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

# dictionary sorted by value
OrderedDict(sorted(d.items(), key=lambda t: t[1]))
# OrderedDict([('pear', 1), ('orange', 2), ('banana', 3), ('apple', 4)])

除了使用内置模块等,我尝试手动解决它。。。

首先,我制作了一个函数,其任务是返回dict的每个项的最小值:

def returnminDict(_dct):
    dict_items = _dct.items()
    list_items = list(dict_items)
    init_items = list_items[0]
    for i in range(len(list_items)):
        if list_items[i][1] > init_items[1]:
           continue
        else:
           init_items = list_items[i]
    return init_items

第二,现在我们有一个函数,它返回一个具有最小值的项。然后我做了一个新的格言,并在格言上循环:

def SelectDictSort(_dct):
    new_dict = {}
    while _dct:
        mindict = returnminDict(_dct)
        new_dict.update(dict((mindict,)))
        _dct.pop(mindict[0])
    return new_dict

我尝试使用SelectDictSort({2:5,5:1,4:3,1:1,0:1,9:2,8:2})。它将返回:

{0: 1, 1: 1, 5: 1, 8: 2, 9: 2, 4: 3, 2: 5}

嗯……我不知道哪一个是正确的,但这是我尝试过的。。。

简单如:sorted(dict1,key=dict1.get)

嗯,实际上可以进行“按字典值排序”。最近,我不得不在代码高尔夫(堆栈溢出问题代码高尔夫:单词频率表)中这样做。简言之,问题是这样的:给定一个文本,计算每个单词遇到的频率,并显示一个按频率递减排序的顶级单词列表。

如果您构建一个字典,将单词作为关键字,将每个单词的出现次数作为值,则此处简化为:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

然后,您可以得到一个单词列表,按使用频率排序,排序(d,key=d.get)-排序将使用单词出现的次数作为排序关键字,在字典关键字上迭代。

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

我写这篇详细的解释是为了说明人们通常所说的“我可以很容易地按关键字对字典进行排序,但我如何按值排序”——我认为最初的文章正试图解决这一问题。解决方案是根据这些值列出一些键,如上所示。