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}]
}]
First off, from Python 3.7+ you can use normal
dictsince it maintains the insertion order.You can re-write your function like:
Test:
output:
Explanation :
You can get the keys from the dictionary itself, no need to pass it to the function.
the iteration part of the
odictis basically iterating through theodictdictionary in parallel.For the expression part of list comp, you need to zip the
keysand the values which get returned from the iteration part.