将有序字典转换为其他格式 [英] Convert ordered dictionary to different format
问题描述
我需要以最小的时间复杂性将给定的有序词典列表转换为其他格式.复制示例代码:
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']]
现在要获得最终结果,没有循环,唯一的选择是map
和lambda
,但是很丑
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屋!