将有序字典转换为其他格式 [英] Convert ordered dictionary to different format

查看:198
本文介绍了将有序字典转换为其他格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以最小的时间复杂性将给定的有序词典列表转换为其他格式.复制示例代码:

I need to convert the given list of ordered dictionaries in a different format with minimal time complexity. Code for reproducing example:

import csv
from collections import OrderedDict

list_of_dicts = [OrderedDict([('key_a','value_a'),('key_b','value_b')]), 
                 OrderedDict([('key_a','value_c'),('key_b','value_d')]),
                 OrderedDict([('key_a','value_e'),('key_b','value_f')])]

需要将以上内容转换为以下内容(不使用显式循环):

Need to convert the above to the following (WITHOUT USING EXPLICIT FOR LOOP):

convertedDictionary = [OrderedDict([('value_a','value_b')]),
                       OrderedDict([('value_c','value_d')]),
                       OrderedDict([('value_e','value_f')])]

推荐答案

第一步:获取列表:足够简单地将dict.values映射到字典:

first step: get the lists: simple enough mapping dict.values to the dicts:

>>> list(map(dict.values,list_of_dicts))
[['value_a', 'value_b'], ['value_c', 'value_d'], ['value_e', 'value_f']]

现在要获得最终结果,没有循环,唯一的选择是maplambda,但是很丑

Now for the final result, without loops, the only alternative is map with lambda but it's ugly

>>> list(map(lambda x : OrderedDict((x,)),map(dict.values,list_of_dicts)))
[OrderedDict([('value_a', 'value_b')]),
 OrderedDict([('value_c', 'value_d')]),
 OrderedDict([('value_e', 'value_f')])]

通过外部列表理解,这会更好(可能更快):

which is much better (and probably faster) with an outer list comprehension:

[OrderedDict((x,)) for x in map(dict.values,list_of_dicts)]

注意:如果每个词典只有1个值,为什么要使用OrderedDict?为什么每个字典只存储一个值?除非这是一个初始化步骤,否则数据模型看起来很可疑.

note: why using OrderedDict if you only have 1 value per dictionary? why storing only one value per dictionary? Unless this is an initialization step, the data model looks dubious.

这篇关于将有序字典转换为其他格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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