Converting Poorly formed dictionary with pandas

27 Views Asked by At

I have a poorly formatted dictionary that uses numbers as keys in a nested dictionary, and not all keys in the top level have the same number of nested items. Example:

 {'Option 1': {'0': 'es_LA', '1': 'de_DE', '2': 'fr_FR'}, 'Option 2': {'0': 'de_DE', '1': 'it_IT', '2': 'ja_JP'}}

Desired outcome is something like

 {'category': 'Option 1', 'locales': ['es_LA', 'de_DE', 'fr_FR']}, {'category': 'Option 2', 'locales': ['de_DE', 'it_IT', 'ja_JP']}

I know it will involve iterating, but am having a hard time figuring out how to get to that point, since the keys are not all the same. Any help would be appreciated.

1

There are 1 best solutions below

0
CDJB On

You can just use a simple list-comprehension - as follows. We use d.items() to iterate over each key, value pair in the original dictionary. For each key, value pair, we want to make a new dictionary consisting of category mapping to the key, and locales mapping to each value from the old dictionary value. Written in full, this is equivalent to:

Code:

>>> d = {'Option 1': {'0': 'es_LA', '1': 'de_DE', '2': 'fr_FR'}, 'Option 2': {'0': 'de_DE', '1': 'it_IT', '2': 'ja_JP'}}
>>> d_new = [{'category': k, 'locales': list(v.values())} for k, v in d.items()]
>>> d_new
[{'category': 'Option 1', 'locales': ['es_LA', 'de_DE', 'fr_FR']},
 {'category': 'Option 2', 'locales': ['de_DE', 'it_IT', 'ja_JP']}]