I want to combine the elements in the multidimensional list.
I have a list the below
[
[
{ 'name': 'q' },
{ 'surname': 'w' },
{ 'email': 'e' }
],
[
{ 'name': 'a' },
{ 'surname': 's' },
{ 'email': 'd' }
]
]
I want to list to be like this;
[
{
'name': 'q',
'surname': 'w',
'email': 'e'
},
{
'name': 'a',
'surname': 's',
'email': 'd'
}
]
How can I do this with Python? Can you help me please?
Thanks.
>Solution :
Use collections.ChainMap to transform each inner list into a single dict (What is the purpose of collections.ChainMap?), and run that in a list comprehension:
data = [
[
{ 'name': 'q' },
{ 'surname': 'w' },
{ 'email': 'e' }
],
[
{ 'name': 'a' },
{ 'surname': 's' },
{ 'email': 'd' }
]
]
from collections import ChainMap
newdata = [dict(ChainMap(*item)) for item in data]
newdata
gives
[{'email': 'e', 'surname': 'w', 'name': 'q'},
{'email': 'd', 'surname': 's', 'name': 'a'}]