Let's say I've got three lists below:
data = [
{"type": "special", "prize": "32220402"},
{"type": "grand", "prize": "99194290"},
[
{"type": "first", "prize": "16525386"},
{"type": "first", "prize": "28467179"},
{"type": "first", "prize": "27854976"},
],
[
{"type": "second", "prize": "6525386"},
{"type": "second", "prize": "8467179"},
{"type": "second", "prize": "7854976"},
],
]
How can I combine all the values in the list above to:
[
{"type": "special", "prize": "32220402"},
{"type": "grand", "prize": "99194290"},
{"type": "first", "prize": "16525386"},
{"type": "first", "prize": "28467179"},
{"type": "first", "prize": "27854976"},
{"type": "second", "prize": "6525386"},
{"type": "second", "prize": "8467179"},
{"type": "second", "prize": "7854976"},
]
What is the syntactically cleanest way to accomplish this?
Thanks for any help!!
CodePudding user response:
This is a possible solution:
[data[0], data[1], *data[2], *data[3]]
If you prefer a more general approach:
[dct for x in data for dct in (x if isinstance(x, list) else (x,))]
CodePudding user response:
If there is a large number, you can use looping as:
result = []
for i in data:
if isinstance(i, list):
for j in i:
result.append(j)
else:
result.append(i)
CodePudding user response:
Looks like you want to flatten embedded lists, and keep the rest as it is. This should do it:
flat = []
for e in data:
if isinstance(e, list):
flat.extend(e)
else:
flat.append(e)