0

I have a dictionary that looks like this:

{'data': [['748','','285','102','76024']]}

and I want to flatten the lists to look like this:

{'data': ['748','','285','102','76024']}

I have tried this from here:

[item for sublist in data.items() for item in sublist]

but it gives me:

['data', [['748', '', '285', '102', '76024', '88', '3', '89%831', '77%', '', '68%632', '19%177', '13%120']]]

Stackcans
  • 351
  • 1
  • 9

1 Answers1

1

Based on the title, I noticed that you might have list of lists in each item in your dictionary. Using itertools.chain() you can merge multiple lists into one:

import itertools
data = {'data': [['748','','285','102','76024']]}
data1 = {'data': [['748','','285','102','76024'], ['12', '13', '14']]}

output = {k: list(itertools.chain(*v)) for k,v in data.items()}   
output1 = {k: list(itertools.chain(*v)) for k,v in data1.items()}   

Output:

# Output
{'data': ['748', '', '285', '102', '76024']}

# Output1
{'data': ['748', '', '285', '102', '76024', '12', '13', '14']}
aminrd
  • 4,300
  • 4
  • 23
  • 45