简体   繁体   English

从dict创建OrderedDict,列表类型的值(按列表值的顺序)

[英]Create OrderedDict from dict with values of list type (in the order of list's values)

It is a bit hard for me to explain it in words, so I'll show an example: 我用文字解释它有点困难,所以我将展示一个例子:

What I have (data is a dict instance): 我有什么(data是一个dict实例):

data = {'a':[4,5,3], 'b':[1,0,2], 'c':[6,7,8]}

What I need ( ordered_data is an OrderedDict instance): 我需要什么( ordered_data是一个OrderedDict实例):

ordered_data = {'b':[0,1,2], 'a':[3,4,5], 'b':[6,7,8]}

The order of keys should be changed with respect to order of items in nested lists 应根据嵌套列表中的项目顺序更改键的顺序

tmp = {k:sorted(v) for k,v in data.items()}
ordered_data = OrderedDict((k,v) for k,v in sorted(tmp.items(), key=lambda i: i[1]))

First sort the values. 首先对值进行排序。 If you don't need the original data , it's OK to do this in place, but I made a temporary variable. 如果您不需要原始data ,可以在适当的位置执行此操作,但我创建了一个临时变量。

key is a function that returns a key to be sorted on. key是一个返回要排序的键的函数。 In this case, the key is the second element of the item tuple (the list), and since lists are comparable, that's good enough. 在这种情况下,键是项元组(列表)的第二个元素,由于列表具有可比性,这就足够了。

You can use OrderedDict by sorting your items and the values : 您可以通过对项目和值进行排序来使用OrderedDict

>>> from operator import itemgetter
>>> from collections import OrderedDict
>>> d = OrderedDict(sorted([(k, sorted(v)) for k, v in data.items()], key=itemgetter(1)))
>>> d
OrderedDict([('b', [0, 1, 2]), ('a', [3, 4, 5]), ('c', [6, 7, 8])])

Usually, you should not worry about the data order in the dictionary itself, and instead, jsut order it when you retrieve the dictionary's contents (ie: iterate over it): 通常,您不必担心字典本身中的数据顺序,而是在检索字典的内容时jsut对它进行排序(即:迭代它):

data = {'a':[4,5,3], 'b':[1,0,2], 'c':[6,7,8]}
for datum in sorted(data.items(), key=lambda item: item[1]):
    ...

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

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