Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python multidimensional list combine

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
  { 
   '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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading