Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten values of every key in python

I have a dictionary like this:

migration_dict = {'30005': ['key42750','key43119', 'key44103', ['key333'],
['key444'], ['keyxx']], '30003': ['key43220', 'key42244','key42230',
['keyzz'], ['kehh']]}

How can I flatten the values of every key in order to have something like this:

migration_dict = {'30005': ['key42750','key43119', 'key44103', 'key333',
'key444', 'keyxx'], '30003': ['key43220', 'key42244','key42230',
'keyzz', 'kehh']}
like image 656
e7lT2P Avatar asked Dec 06 '25 08:12

e7lT2P


1 Answers

You can write a recursive function to flatten the value lists and use it in a dictionary comprehension to build a new dictionary:

def flatten(lst):
   for x in lst:
      if isinstance(x, list):
         for y in flatten(x): # yield from flatten(...) in Python 3
            yield y           #
      else:
         yield x

migration_dict = {k: list(flatten(v)) for k, v in dct.items()}
print(migration_dict)
# {'30005': ['key42750', 'key43119', 'key44103', 'key333', 'key444', 'keyxx'], '30003': ['key43220', 'key42244', 'key42230', 'keyzz', 'kehh']}

It handles any nesting depth in the dict value lists.

like image 143
Moses Koledoye Avatar answered Dec 08 '25 21:12

Moses Koledoye