Python multidimensional list combine

Viewed 48

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.

3 Answers

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'}]

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.

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)
Related