single dictionary containing multiple list of lists under the same key. Looking to combining the all values under the same key into a single list

Viewed 38

I have a single dictionary that contains multiple lists under a single key - here is an example of the output of my dictionary:

print(dic)

Output:

{1: [[1, 2, 3, 4, 5, 6, 7],
  [5, 1, 4, 34, 3, 65, 0, 2],
  [2, 5, 4, 5, 7, 8, 4, 7]],
 2: [[1, 5, 4, 5, 0, 1, 4, 6],
  [2, 2, 3, 5, 6, 6, 3, 9]],
 3: [[12, 35, 42, 53, 70, 71, 74, 76],
  [6, 11, 16, 17, 38, 62, 66, 77]]}

I am looking to create a single list for all lists under each key. So an output example of what i am looking for would look like this:

{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
 2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
 3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}

I have tried a dict comprehension to little success as well as a for loop where i iterate over dic.items().

3 Answers

You can use a dictionary comprehension:

{key: [[item for sublist in value for item in sublist]] for key, value in data.items()}

This outputs:

{
 1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
 2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
 3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]
}

Try with itertools.chain.from_iterable:

>>> import itertools

>>> {k : [list(itertools.chain.from_iterable(v))] for k,v in dct.items()}
{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
 2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
 3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}

Using itertools.chain:

from itertools import chain

out = {k: [list(chain.from_iterable(l))]
       for k,l in dic.items()}

Output:

{1: [[1, 2, 3, 4, 5, 6, 7, 5, 1, 4, 34, 3, 65, 0, 2, 2, 5, 4, 5, 7, 8, 4, 7]],
 2: [[1, 5, 4, 5, 0, 1, 4, 6, 2, 2, 3, 5, 6, 6, 3, 9]],
 3: [[12, 35, 42, 53, 70, 71, 74, 76, 6, 11, 16, 17, 38, 62, 66, 77]]}
Related