2
list_data = [['a', 'b', 'c', 'd'],
         ['hello', 'mellow', 'fellow', 'jello'],
         [2, 3, 6, 8]]

flattened = []
for data in list_data:
    for x in data:
        flattened.append(x)

print(flatenned)

gives me:

['a', 'b', 'c', 'd', 'hello', 'mellow', 'fellow', 'jello', 2, 3, 6, 8]

How, can I rather flatten this lits to (below) in a most simple way:

['a', 'hello', 2, 'b', 'mellow', 3,  'c', 'fellow', 6, 'd', 'jello', 8]

and to dictionary:

['a': ['hello' 2], 'b': ['mellow', 3], 'c': ['fellow', 6], 'd': ['jello', 8]]

Explanation of the process would be helpful.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
everestial007
  • 6,665
  • 7
  • 32
  • 72

2 Answers2

4

You can use zip to transpose the matrix:

[y for x in zip(*list_data) for y in x]
# ['a', 'hello', 2, 'b', 'mellow', 3, 'c', 'fellow', 6, 'd', 'jello', 8]

To get the dictionary:

dict(zip(list_data[0], zip(*list_data[1:])))
# {'a': ('hello', 2), 'b': ('mellow', 3), 'c': ('fellow', 6), 'd': ('jello', 8)}

Description:

Dictionary is reported as keys and values, d[k,v].

so, first part list_data[0] picks keys from the first index (0) of every list, and the latter part zip(*list_data[1:]) adds the remaining elements of the list as the values for that key.

Psidom
  • 209,562
  • 33
  • 339
  • 356
  • I just added some description for the dictionary. Just wanted to clarify something for myself. – everestial007 Feb 06 '17 at 15:44
  • The edit looks good. Just the keys don't include the `zip`, the first `zip` is used to combine keys and values into pairs. I modified your description a little bit. – Psidom Feb 06 '17 at 15:49
  • Just to clarify why is there a simple bracket in this `dict`. Does that matter at all though. – everestial007 Feb 06 '17 at 16:03
  • 1
    The parenthesis around the values means it's a tuple instead of list, under most circumstances, it should not affect your result. But you can convert them to list by `{k: list(v) for k, v in my_dict.items()}` assuming `my_dict` is the dictionary you get. – Psidom Feb 06 '17 at 16:06
  • Psidom - Would you be give a little guidance on a problem I am facing. I want to run an `applymap function for a pandas dataframe using a groupby`. http://stackoverflow.com/questions/42171132/is-it-possible-to-do-applymap-using-the-groupby-in-pandas I think this problem is similar to using a unique keys in dict, but I want to use dataframe since the real data is going to be huge. thanks – everestial007 Feb 11 '17 at 15:16
3

For flattening the list, you may use itertools.chain with zip as:

>>> from itertools import chain

>>> list(chain(*zip(*list_data)))
['a', 'hello', 2, 'b', 'mellow', 3, 'c', 'fellow', 6, 'd', 'jello', 8]

For mapping the values to desired dict, you may use zip with dictionary comprehension expression as:

>>> {i: [j, k] for i, j, k in zip(*list_data)}
{'a': ['hello', 2], 'c': ['fellow', 6], 'b': ['mellow', 3], 'd': ['jello', 8]}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126