python字典基于值降序排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20577840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:46:09  来源:igfitidea点击:

python dictionary sorting in descending order based on values

pythondictionary

提问by NullException

I want to sort this dictionary d based on value of sub key key3 in descending order. See below:

我想根据子键 key3 的值按降序对字典 d 进行排序。见下文:

d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }

So final dictionary would look like this.

所以最终的字典看起来像这样。

d = { '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
    }

My approach was to form another dictionary e from d, whose key would be value of key3 and then use reversed(sorted(e)) but since value of key3 can be same, so dictionary e lost some of the keys and their values. makes sense?

我的方法是从 d 形成另一个字典 e,其键将是 key3 的值,然后使用 reversed(sorted(e)) 但由于 key3 的值可以相同,因此字典 e 丢失了一些键及其值。说得通?

How I can accomplish this? This is not a tested code. I am just trying to understand the logic.

我怎么能做到这一点?这不是经过测试的代码。我只是想了解逻辑。

采纳答案by abarnert

Dictionaries do not have any inherent order. Or, rather, their inherent order is "arbitrary but not random", so it doesn't do you any good.

字典没有任何固有的顺序。或者,更确切地说,它们的固有顺序是“任意的但不是随机的”,所以这对您没有任何好处。

In different terms, your dand your ewould be exactly equivalent dictionaries.

换句话说,youd和 youre将是完全等效的字典。

What you can do here is to use an OrderedDict:

你可以在这里做的是使用一个OrderedDict

from collections import OrderedDict
d = { '123': { 'key1': 3, 'key2': 11, 'key3': 3 },
      '124': { 'key1': 6, 'key2': 56, 'key3': 6 },
      '125': { 'key1': 7, 'key2': 44, 'key3': 9 },
    }
d_ascending = OrderedDict(sorted(d.items(), key=lambda kv: kv[1]['key3']))
d_descending = OrderedDict(sorted(d.items(), 
                                  key=lambda kv: kv[1]['key3'], reverse=True))

The original dhas some arbitrary order. d_ascendinghas the order you thoughtyou had in your original d, but didn't. And d_descendinghas the order you want for your e.

原件d有一些随意的顺序。d_ascending具有您认为在原始文件d中具有但没有的顺序。并d_descending为您的e.



If you don't really need to use eas a dictionary, but you just want to be able to iterate over the elements of din a particular order, you can simplify this:

如果您真的不需要e用作字典,但您只想能够以d特定顺序迭代 的元素,则可以简化此操作:

for key, value in sorted(d.items(), key=lambda kv: kv[1]['key3'], reverse=True):
    do_something_with(key, value)


If you want to maintain a dictionary in sorted order across any changes, instead of an OrderedDict, you want some kind of sorted dictionary. There are a number of options available that you can find on PyPI, some implemented on top of trees, others on top of an OrderedDictthat re-sorts itself as necessary, etc.

如果您想在任何更改中按排序顺序维护字典,而不是OrderedDict,您需要某种排序的字典。您可以在 PyPI 上找到许多可用的选项,有些是在树的顶部实现的,有些是在OrderedDict必要时重新排序的,等等。

回答by John Zwinck

Python dicts are not sorted, by definition. You cannot sort one, nor control the order of its elements by how you insert them. You might want to look at collections.OrderDict, which even comes with a little tutorial for almost exactly what you're trying to do: http://docs.python.org/2/library/collections.html#ordereddict-examples-and-recipes

根据定义,Python 字典没有排序。您无法对其进行排序,也无法通过插入元素的方式来控制其元素的顺序。您可能想查看 collections.OrderDict,它甚至附带了一个几乎完全符合您要执行的操作的小教程:http: //docs.python.org/2/library/collections.html#ordereddict-examples-和-食谱

回答by Dibin Joseph

you can make use of the below code for sorting in descending order and storing to a dictionary:

您可以使用以下代码按降序排序并存储到字典中:

        listname = []  
        for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):  
            diction= {"value":value, "key":key}  
            listname.append(diction)

回答by neetu chaudhary

List

列表

dict = {'Neetu':22,'Shiny':21,'Poonam':23}
print sorted(dict.items())
sv = sorted(dict.values())
print sv

Dictionary

字典

d = []
l = len(sv)
while l != 0 :
    d.append(sv[l - 1])
    l = l - 1
print d`

回答by Shafiq

A short example to sort dictionary is desending order for Python3.

对字典进行排序的一个简短示例是 Python3 的降序。

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print(r, a1[r])

Following will be the output

以下将是输出

e 30
b 13
d 4
c 2
a 1

回答by Vegard Sangolt

sort dictionary 'in_dict' by value in decreasing order

按值按降序对字典“in_dict”进行排序

sorted_dict = {r: in_dict[r] for r in sorted(in_dict, key=in_dict.get, reverse=True)}

example above

上面的例子

sorted_d = {r: d[r] for r in sorted(d, key=d.get('key3'), reverse=True)}

回答by Hemang Vyas

You can use the operator to sort the dictionary by values in descending order.

您可以使用该运算符按值按降序对字典进行排序。

import operator

d = {"a":1, "b":2, "c":3}
cd = sorted(d.items(),key=operator.itemgetter(1),reverse=True)

The Sorted dictionary will look like,

Sorted 字典看起来像,

cd = {"c":3, "b":2, "a":1}

Here, operator.itemgetter(1) takes the value of the key which is at the index 1.

这里,operator.itemgetter(1) 取索引为 1 的键的值。