Reputation: 5323
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.
Upvotes: 3
Views: 85
Reputation: 251096
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.
Upvotes: 4