I have a list of list of dictionaries :
liste = [[{"template_id": 32, "template_name" : "test1"}, {"template_id": 34, "template_name" : "test2"}],[{"template_id": 34, "template_name" : "test3"}, {"template_id": 35, "template_name" : "test4"},{"template_id": 36, "template_name" : "test5"}]]
I want to merge them like this :
[{"template_id": 32, "template_name" : "test1"},{"template_id": 34, "template_name" : "test3"}, {"template_id": 34, "template_name" : "test2"},{"template_id": 35, "template_name" : "test4"},{"template_id": 36, "template_name" : "test5"}]
I have tried to do it like this but it does not work properly since i'm not a Python expert :
for j in range(len(liste)):
for i in range(len(liste[j]) 1):
try :
print(f"F={f},j={j}, i={i} ")
optimized_list.append(liste[i][j])
#print(liste[i][j]['template_name'])
except IndexError:
pass
CodePudding user response:
You can use itertools.chain
:
from itertools import chain
liste = [[{"template_id": 32, "template_name" : "test1"}, {"template_id": 34, "template_name" : "test2"}],[{"template_id": 34, "template_name" : "test3"}, {"template_id": 35, "template_name" : "test4"},{"template_id": 36, "template_name" : "test5"}]]
output = [*chain.from_iterable(liste)]
print(output)
# [{'template_id': 32, 'template_name': 'test1'},
# {'template_id': 34, 'template_name': 'test2'},
# {'template_id': 34, 'template_name': 'test3'},
# {'template_id': 35, 'template_name': 'test4'},
# {'template_id': 36, 'template_name': 'test5'}]
CodePudding user response:
You can use numpy
, and use concatenate()
function and flat
attribute to get your desired result.
import numpy
liste = [[{"template_id": 32, "template_name" : "test1"},
{"template_id": 34, "template_name" : "test2"}],[{"template_id":
34, "template_name" : "test3"}, {"template_id": 35,
"template_name" : "test4"},{"template_id": 36, "template_name" :
"test5"}]]
flat_list = list(numpy.concatenate(liste).flat)
print(flat_list)