从列表理解创建有序的dict? [英] create ordered dict from list comprehension?

查看:178
本文介绍了从列表理解创建有序的dict?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是列表解析



其中




  • 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] 


Here is a list comprehension:

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 to L[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆