transform ordered dictionaries to list of dictionaries iteratively

155 Views Asked by At

EDIT: I realized I made a mistake in my data structure and updated it.

I have an ordered dict with some values as list and some as list of lists:

odict = OrderedDict([('A', [33]),
                     ('B',
                         [[{'AA': 'DOG', 'BB': '2'},
                           {'AA': 'CAT', 'BB': '1'}]]),
                     ('C',
                         [['01','012']])
                     ])

I am currently manually adding the keys and values in this function:

def odict_to_listdict(odict, key1: str, key2: str, key3: str) -> list:
    return [{key1: v, key2: v2, key3: v3} for v1, v2, v3 in \
         zip(odict[key1], odict[key2], odict[key3])]
odict_to_listdict(odict,'key1','key2','key3')

that gives me the expected output of a list of dictionaries:

[{'A': 33,
  'B': [{'AA': 'DOG', 'BB': '2'}, {'AA': 'CAT', 'BB': '1'}],
  'C': ['01', '012']}]

I plan to add more keys, values, how do I iterate through the ordered dict without explicitly typing the keys while maintaining the expected output, for example:

[{'A': 33,
  'B': [{'AA': 'DOG', 'BB': '2'}, {'AA': 'CAT', 'BB': '1'}],
  'C': ['01', '012']}],
  'D': 42,
  'E': [{'A': 1}]
}]
1

There are 1 best solutions below

1
On

First off, from Python 3.7+ you can use normal dict since it maintains the insertion order.

You can re-write your function like:

def odict_to_listdict(odict):
    keys = list(odict)
    return [dict(zip(keys, i)) for i in zip(*odict.values())]

Test:

from collections import OrderedDict

odict = OrderedDict()
odict['key1'] = ['1', '2']
odict['key2'] = ['Apple', 'Orange']
odict['key3'] = ['bla', 'bla']

def odict_to_listdict(odict):
    keys = list(odict)
    return [dict(zip(keys, i)) for i in zip(*odict.values())]

print(odict_to_listdict(odict))

output:

[{'key1': '1', 'key2': 'Apple', 'key3': 'bla'}, {'key1': '2', 'key2': 'Orange', 'key3': 'bla'}]

Explanation :
You can get the keys from the dictionary itself, no need to pass it to the function.

the iteration part of the odict is basically iterating through the odict dictionary in parallel.

For the expression part of list comp, you need to zip the keys and the values which get returned from the iteration part.