从列表理解创建有序的dict? [英] create ordered dict from list comprehension?
问题描述
其中
-
L
是有序字典列表(即collection.OrderedDict的对象),其中字典具有相同的键集。 -
d
是另一个有序字典,它也具有与先前订购的字典相同的一组键。 -
对于每个
键
,d [key]
是可以应用于L [i] [key]
的功能,即d [key](L [i] [key])
。
所有给定的字典都是排序的,并且键的顺序相同。
但代码将创建无序字典。与给定的订阅字典相同的关键顺序如何创建一个有序的字典?
collections.OrderedDict
只不过是一个dict,其中包含元素的顺序。所以你可以用它的构造函数创建一个这样的
[OrderedDict((k,d [k](v))for k,v)in l.iteritems())for L in L]
L = [{k: d[k](v) for (k, v) in l.iteritems()} for l in L]
where
L
is a list of ordered dictionaries (i.e. objects of collections.OrderedDict), where the dictionaries have the same set of keys.d
is another ordered dictionary, which also has the same set of keys as the previous ordered dictionaries.For each
key
,d[key]
is a function which can apply toL[i][key]
, i.e.d[key](L[i][key])
.
All the given dictionaries are ordered dicts, and have the same order in their keys.
But the code will create an unordered dictionary. How can I create an ordered dict in the same key order as the given ordered dictionaries?
collections.OrderedDict
is nothing but a dict, which remembers the order in which the elements are included in it. So you can create one with its constructor like this
[OrderedDict((k, d[k](v)) for (k, v) in l.iteritems()) for l in L]
这篇关于从列表理解创建有序的dict?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!