Home > Software design >  Expand OrderedDict with list values to a list of dictionaries
Expand OrderedDict with list values to a list of dictionaries

Time:03-14

I have an OrderedDict with a list of values:

OrderedDict([('key1', ['value1', 'value2']),
             ('key2',
              [[{'name': ['A', 'B'], 'amount': ['1', '2']}],
               [{'name': ['C', 'D'], 'amount': ['3', '4']}]])])

I'd like to transform this to a list of dictionaries where the lists in the values of the inner dictionaries expanded across separate dictionaries in a list:

[{'key1': 'value1',
  'key2': [{'name': 'A', 'amount': 1}, {'name': 'B', 'amount': 2}]},
 {'key1': 'value2',
  'key2': [{'name': 'C', 'amount': 3}, {'name': 'D', 'amount': 4}]}]

CodePudding user response:

We could use zip to traverse values under both "key1" and "key2" together and append to an output list as we iterate. Moreover, the values of the inner dict have to be traversed together as well, so we unpack the values of lst[0] and use zip yet to construct the inner dictionary:

out = []
for v, lst in zip(data['key1'], data['key2']):
    d = {'key1': v, 'key2': []}
    for tpl in zip(*lst[0].values()):
        mid = {key: val for key, val in zip(lst[0], tpl)}
        d['key2'].append(mid)
    out.append(d)

The same code as a nested comprehension:

out = [{'key1': v, 'key2': [{key: val for key, val in zip(lst[0], tpl)} for tpl in zip(*lst[0].values())]} for v, lst in zip(data['key1'], data['key2'])]

Output:

[{'key1': 'value1',
  'key2': [{'name': 'A', 'amount': '1'}, {'name': 'B', 'amount': '2'}]},
 {'key1': 'value2',
  'key2': [{'name': 'C', 'amount': '3'}, {'name': 'D', 'amount': '4'}]}]
  • Related