简体   繁体   English

按dict值排序dicts列表

[英]Sorting a list of dicts by dict values

I have the following list of dictionaries 我有以下词典列表

a = [{23:100}, {3:103}, {2:102}, {36:103}, {43:123}]

How can I sort it to get: 如何对其进行排序以获得:

a = [{43:123}, {3:103}, {36:103}, {2:102}, {23:100}]

I mean, to sort the list by its dicts' values, in descending order. 我的意思是,按照其dicts的值按降序对列表进行排序。

In addition to brandizzi's answer, you could go with: 除了brandizzi的答案,你可以选择:

sorted(a, key=dict.values, reverse=True)

Pretty much the same thing, but possibly more idiomatic. 几乎相同的东西,但可能更惯用。

>>> sorted(a, key=lambda i: i.values()[0], reverse=True)
[{43: 123}, {3: 103}, {36: 103}, {2: 102}, {23: 100}]

You can pass a key parameter to the list.sort() method, so the comparison will be made in function of the returning value of key : 您可以将一个key参数传递给list.sort()方法,因此将根据key的返回值进行比较:

>>> a = [{23:100}, {3:103}, {2:102}, {36:103}, {43:123}]
>>> a.sort(key=lambda d: d.values()[0], reversed=True)
>>> a
[{23: 100}, {2: 102}, {3: 103}, {36: 103}, {43: 123}]

In this case, the key is a function which receives a dictionary d and gets a list of its value with .values() . 在这种情况下,键是一个函数,它接收字典d并使用.values()获取其值的列表。 Since there is just one value, we get this only value from the returned list. 由于只有一个值,我们从返回的列表中获取此值。 Then, the list.sort() method will compare those returned values, instead of the dictionaries themselves, when sorting. 然后, list.sort()方法将在排序时比较那些返回的值,而不是字典本身。

In python 3, the other answers no longer work because dict.values() now returns a dict view object rather than a list. 在python 3中,其他答案不再有效,因为dict.values()现在返回一个dict视图对象而不是列表。 To extract the value from the view object, we can use a combination of iter and next : 要从视图对象中提取值,我们可以使用iternext的组合:

a.sort(key=lambda dic: next(iter(dic.values())), reverse=True)

I'd rather use (or at least keep in mind) .itervalues() 我宁愿使用(或至少记住) .itervalues()

In [25]: sorted(a, key=lambda x: next(x.itervalues()), reverse=True)
Out[25]: [{43: 123}, {36: 103}, {2: 102}, {23: 100}, {3: 103}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM