2

I was hoping that there might be someway to use a comprehension to do this, but say I have data that looks like this:

data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]

My ultimate goal is to create a dictionary where the first nested list holds the keys and the remaining lists hold the values:

{'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

I have tried something like this that gets me close, but as you can tell I am having trouble appending the list in the dictionary values and this code is just overwriting:

d = {data[0][c]: [] + [col] for r, row in enumerate(data) for c, col in enumerate(row)}
>>> d
{'c': [6], 'a': [4], 'b': [5]}
ayhan
  • 70,170
  • 20
  • 182
  • 203
LMc
  • 12,577
  • 3
  • 31
  • 43

1 Answers1

6

You can use zip in a dict comprehension:

{z[0]: list(z[1:3]) for z in zip(*data)}
Out[16]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

How it works:

zip will take the transpose:

list(zip(['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]))
Out[19]: [('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

However, your data is a list of lists, so in order to make sure Python doesn't see a single list but sees three seperate lists, you need zip(*data) instead of zip(data). There are several posts on the use of *: (1), (2), (3).

list(zip(*data))
Out[13]: [('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

And in the dict comprehension you are taking the first elements as the keys and the remaining two as the values.

Community
  • 1
  • 1
ayhan
  • 70,170
  • 20
  • 182
  • 203