3

Assuming I have a list of lists:

ll = [
         ['a', 'b', 'c'],
         [1, 2, 3],
         [4, 5, 6],
         [7, 8, 9]
     ]

I want to convert it into a dictionary:

dl = dict(
    a = [1, 4, 7],
    b = [2, 5, 8],
    c = [3, 6, 9]
)

I currently have following code that does this:

dl = dict((k, 0) for k in ll[0])
for i in range(1, len(ll)):
    for j in range(0, len(ll[0])):
        dl[ll[0][j]].append(ll[i][j])

Is there a simpler/elegant way to do this?

I am using Python 3, if that matters.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Aaron S
  • 5,023
  • 4
  • 29
  • 30

1 Answers1

4

Use a dict-comprehension with zip():

>>> {k: v for k, *v in zip(*ll)}
{'c': [3, 6, 9], 'a': [1, 4, 7], 'b': [2, 5, 8]}

Here zip() with splat operator (*) transposes the list items:

>>> list(zip(*ll))
[('a', 1, 4, 7), ('b', 2, 5, 8), ('c', 3, 6, 9)]

Now we can loop over this iterator return by zip and using the extended iterable packing introduced in Python 3 we can get the key and values very cleanly from each tuple.

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504