简体   繁体   English

python按列表的内部列表排序字典

[英]python sorting dictionary by inner list of lists

I am using Python 2.5. 我正在使用Python 2.5。 I have a dictionary with a list of lists as values 我有一本字典,其中有一个列表列表作为值

{'a': [['6', 3]], 'b': [['5', 1], ['6', 5]], 'c': [['446', 2],['6', 11],['67', 86]] }

I want to sort it by the 2nd element of the first list item, so, the above would be sorted like this: 我想按第一个列表项的第二个元素对其进行排序,因此,以上内容将按以下方式进行排序:

'b': [['5', 1], ['6', 5]], 
'c': [['446', 2],['6', 11],['67', 86]]
'a': [['6', 3]]

Any suggestions? 有什么建议么?

Thanks Scott 谢谢斯科特

A dictionary itself is unordered, so you can't sort it per se. 字典本身是无序的,因此您本身无法对其进行排序。 If you want to create a sorted list of the key-value pairs, you can do that: 如果要创建键值对的排序列表,可以执行以下操作:

sorted(myDict.iteritems(), key=lambda x: x[1][0][1])

iteritems returns an iterable of (key, value) pairs, so x[1][0][1] there means "take the second element of this pair (which is the value), and take the first element of that (which is the first list in the list of lists) and take the second element in that --- in order words, the second element in the first list, which is what you want. iteritems返回一个可迭代的(键,值)对,因此x[1][0][1]意思是“取该对的第二个元素(即值),并取该对的第一个元素(即值)列表中的第一个列表),然后以该顺序中的第二个元素---按顺序排列,这就是您想要的第一个列表中的第二个元素。

Dictionaries have no order. 字典没有顺序。

However, there is a class in the standard library called collections.OrderedDict that retains the order of insertion. 但是,标准库中有一个称为collections.OrderedDict的类,该类保留插入顺序。 And you can create one like this: 您可以这样创建一个:

>>> collections.OrderedDict(sorted(myDict.iteritems(), key=lambda x: x[1][0][1])
OrderedDict([('b', [['5', 1], ['6', 5]]), ('c', [['446', 2], ['6', 11], ['67', 86]]), ('a', [['5', 4]])])

myDict.iteritems() returns a sequence of (key, value) tuple s. myDict.iteritems()返回一个(key, value) tuple s的序列。 (You can also use items , which will return the sequence as a list instead of an iterator—but it will work in Python 3, which iteritems will not.) (您也可以使用items ,它将返回序列而不是迭代器的列表,但是它将在Python 3中iteritems ,而iteritems则不能。)

sorted sorts them by the key . key sorted它们sorted

The key is a function that takes the value from one of these tuple s, the 2nd element of that value , and the 1st element of that 2nd element, which is what you wanted to sort by. key是一个函数,它从这些tuple之一,该value的第二个元素和该第二个元素的第一个元素中获取value ,这就是您要进行排序的依据。

The OrderedDict class does not exist in Python 2.5, but it's implemented in pure Python. OrderedDict类在Python 2.5中不存在,但在纯Python中实现。 If you look at the docs for 2.7, there's a link to the code , which you can copy and paste into your 2.5 program. 如果您查看2.7 的文档 ,则有指向该代码的链接,您可以将其复制并粘贴到2.5程序中。 Or you can use the ActiveState recipe that was borrowed into the standard library, or look for a module at PyPI that does it for you. 或者,您可以使用借入到标准库中的ActiveState配方,或者在PyPI上寻找适合您的模块。

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

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