-4

I have a list that contains multiple lists and I want to transform the first list into keys and the subsequent lists into values, without the use of pandas.

Example:

list = [[a, b, c],[1 ,2, 3], [4, 5, 6]....]

How can I transform that into this:

dict = {a: [1, 4, 7], b: [2, 5, 8].....}
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • 1
    Are all the lists of the same size? – Joe Ferndz Aug 18 '20 at 03:45
  • Also have you written any code that can help us understand what you have tried? – Joe Ferndz Aug 18 '20 at 03:51
  • Learn to use [`zip`](https://docs.python.org/3.3/library/functions.html#zip) with [dict comprehension](https://stackoverflow.com/questions/14507591/python-dictionary-comprehension). – Henry Yik Aug 18 '20 at 03:58
  • Does this answer your question? [Creating a dictionary with list of lists in Python](https://stackoverflow.com/questions/9858096/creating-a-dictionary-with-list-of-lists-in-python) – Gino Mempin Aug 18 '20 at 04:19

1 Answers1

2
lst = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]]
dct = {l[0]: list(l[1:]) for l in zip(*lst)}
# {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]}

This makes use of zip() and the unpacking operator * to "rotate" the list lst (turn it into [['a', 1, 4], ['b', 2, 5], ['c', 3, 6]]). This is a fairly common idiom.

Then we just iterate over each of those sublists in a dict comprehension, assign the zeroth element as the key, and the rest of the elements as the value.

Note that by default zip() returns tuples instead of lists, so we have to typecast l[1:] to a list if we want to be able to modify it later. This may not be necessary in your use case.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53