1

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.

CDJB
  • 14,043
  • 5
  • 29
  • 55
corn
  • 11
  • 1
  • welcome to stack overflow! you'll get best results here if you try writing some code to solve this first, and include it here in your question. then people will more quickly pitch in to help you get to a good solution – Max Power Feb 02 '20 at 19:24

1 Answers1

1

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']}]
CDJB
  • 14,043
  • 5
  • 29
  • 55