如何使用值对字典进行排序,以及如何访问密钥

Ash*_*ary 2 python dictionary python-3.x

dic = {'Tea': 35, 'Coffee': 35, 'Chocolate': 10}
Run Code Online (Sandbox Code Playgroud)

我想按降序排列这个字典,但我怎么才能访问密钥呢?

示例代码:

for x in sorted(dic.values()):
    print(key, dic[key])
Run Code Online (Sandbox Code Playgroud)

我还希望输出在值相等时按键按字母顺序排序.

预期产出:

Coffee 35
Tea 35
Chocolate 10
Run Code Online (Sandbox Code Playgroud)

Gar*_*tty 9

你想要的是提供元组dict.items()方法(key, value).

要按值排序,您可以使用一种key方法,在这种情况下,a operator.itemgetter()从元组中取第二个值进行排序,然后设置reverse属性以按照您想要的顺序获取它们.

>>> from operator import itemgetter
>>> dic={'Tea': 35, 'Coffee': 35, 'Chocolate': 10}
>>> for key, value in sorted(dic.items(), key=itemgetter(1), reverse=True):
...     print(key, value)
... 
Tea 35
Coffee 35
Chocolate 10
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想按键排序作为辅助排序,我们可以简单地传递一个值元组,Python将排序第一个值,然后是第二个,等等...唯一的问题是使用反向意味着我们得到他们的顺序错了.作为一个黑客,我们只是使用值的负面版本进行排序而不反向:

>>> for key, value in sorted(dic.items(), key=lambda x: (-x[1], x[0])):
...     print(key, value)
... 
Coffee 35
Tea 35
Chocolate 10
Run Code Online (Sandbox Code Playgroud)

  • @ user1374499没有任何迹象表明咖啡和茶的排序不是任意的 - Python dicts是任意排序的,所以一个实现可以很容易地给你的输出. (2认同)

Sve*_*ach 7

一种选择:

for key in sorted(dic, key=dic.get, reverse=True):
    print(key,dic[key])
Run Code Online (Sandbox Code Playgroud)

这对字典的键进行排序,但dic.get用作键函数,从而有效地按值排序.您的示例输出表明您要按降序排序,因此我包含了reverse=True.

编辑:如果您的字典值实际上是计数,您可以考虑使用collections.Counter而不是dicitonary.该类有一个方法most_common(),以所需的顺序返回项目.