Creating a dictionary with key / values ​​coming from a list of lists

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 to a dictionary:

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

      

I currently have the 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 an easier / more elegant way to do this?

I am using Python 3 if that matters.

+3


source to share


1 answer


Use the dict definition 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 the splat ( *

) operator wraps the list items:



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

      

Now we can iterate over this iterator return on zip

and using the advanced iterative boxing introduced in Python 3 we can get the key and is very different from each tuple.

+4


source







All Articles