简体   繁体   English

按值对字典列表进行排序

[英]Sort a list of dictionaries by value

I have a list of dictionaries, of the form: 我有以下形式的词典列表:

neighbour_list = [{1:4}, {3:5}, {4:9}, {5:2}]

I need to sort the list in order of the dictionary with the largest value. 我需要按照字典中具有最大价值的顺序对列表进行排序。 So, for the above code the sorted list would look like: 因此,对于上面的代码,排序后的列表如下所示:

sorted_list = [{4:9}, {3:5}, {1:4}, {5:2}]

Each dictionary within the list only has one mapping. 列表中的每个词典只有一个映射。

Is there an efficient way to do this? 有一种有效的方法可以做到这一点吗? Currently I am looping through the list to get the biggest value, then remembering where it was found to return the largest value, but I'm not sure how to extend this to be able to sort the entire list. 目前,我正在遍历列表以获取最大的值,然后记得在哪里发现它返回了最大的值,但是我不确定如何扩展此范围以能够对整个列表进行排序。

Would it just be easier to implement my own dict class? 实现我自己的dict类会更容易吗?

EDIT: here is my code for returning the dictionary which should come 'first' in an ideally sorted list. 编辑:这是我的代码,用于返回理想排序列表中应排在第一位的字典。

temp = 0
element = 0

for d in list_of_similarities:
    for k in d:
        if (d[k] > temp):
            temp = d[k]
            element = k
            dictionary = d

first = dictionary[element]

You can use an anonymous function as your sorting key to pull out the dict value (not sure if i've done this the most efficient way though: 您可以使用匿名函数作为排序键来提取dict值(虽然不确定我是否以最有效的方式完成了此操作:

sorted(neighbour_list, key = lambda x: tuple(x.values()), reverse=True)
[{4: 9}, {3: 5}, {1: 4}, {5: 2}]

Note we need to coerce x.values() to a tuple, since in Python 3, x.values() is of type "dict_values" which is unorderable. 请注意,我们需要将x.values()强制x.values()为元组,因为在Python 3中, x.values()的类型为“ dict_values”,无法排序。 I guess the idea is that a dict is more like a set than a list (hence the curly braces), and there's no (well-) ordering on sets; 我想这个主意是,字典比列表更像一个集合(因此花括号),并且集合上没有(井井有条)排序。 you can't use the usual lexicographic ordering since there's no notion of "first element", "second element", etc. 您不能使用通常的字典顺序,因为没有“第一个元素”,“第二个元素”等概念。

You could list.sort using the dict values as the key. 您可以使用dict值作为键进行list.sort

neighbour_list.sort(key=lambda x: x.values(), reverse=1)

Considering you only have one value, for python2 you can just call next on itervalues to get the first and only value: 考虑到只有一个值,对于python2,您可以在itervalues上调用next来获取第一个也是唯一的值:

neighbour_list.sort(key=lambda x: next(x.itervalues()), reverse=1)
print(neighbour_list)

For python3, you cannot call next on dict.values , it would have to be: 对于python3,您不能在dict.values上调用next,它必须是:

neighbour_list.sort(key=lambda x: next(iter(x.values())), reverse=1)

And have to call list on dict.values : 并且必须在dict.values上调用list

neighbour_list.sort(key=lambda x: list(x.values()), reverse=1)

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

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