Reputation: 221
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')])]
Upvotes: 3
Views: 46
Reputation: 140266
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']]
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)]
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.
Upvotes: 3