Python multidimensional list combine

Question:

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.

Asked By: phythonnewbee

||

Answers:

You just seem to want to merge multiple dictionaries:

>>> from functools import reduce
>>> from operator import ior
>>> [reduce(ior, mps, {}) for mps in lst]
[{'name': 'q', 'surname': 'w', 'email': 'e'},
 {'name': 'a', 'surname': 's', 'email': 'd'}]

Here, reduce is a shortcut to merge all dictionaries with a for loop, which is basically equivalent to:

>>> def merge_dicts(dicts):
...     res = {}
...     for mp in dicts:
...         res |= mp
...     return res
... 
>>> [merge_dicts(mps) for mps in lst]
[{'name': 'q', 'surname': 'w', 'email': 'e'},
 {'name': 'a', 'surname': 's', 'email': 'd'}]

Because the merge uses the in place operator, there is no extra overhead.

Answered By: Mechanic Pig

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'}]
Answered By: 9769953

the easiest way, in my opinion. It only works if you know the number of items in your inner lists.

new_list = []
for l in my_list:
  d = dict(**(l[0]), **(l[1]), **(l[2]))
  new_list.append(d)

if you don’t know the number of items, you can use:

new_list = []
for l in my_list:
  d = {}
  for i in l:
    d.update(i)
  new_list.append(d)
Answered By: julianofischer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.