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']}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With