Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?

I have a list of strings parsed from somewhere, in the following format:

[key1, value1, key2, value2, key3, value3, ...]

I'd like to create a dictionary based on this list, like so:

{key1:value1, key2:value2, key3:value3, ...}

An ordinary for loop with index offsets would probably do the trick, but I wonder if there's a Pythonic way of doing this. List comprehensions seem interesting, but I can't seem to find out how to apply them to this particular problem.

Any ideas?

like image 678
KennyDeriemaeker Avatar asked Jul 21 '10 19:07

KennyDeriemaeker


1 Answers

You can try:

dict(zip(l[::2], l[1::2]))

Explanation: we split the list into two lists, one of the even and one of the odd elements, by taking them by steps of two starting from either the first or the second element (that's the l[::2] and l[1::2]). Then we use the zip builtin to the two lists into one list of pairs. Finally, we call dict to create a dictionary from these key-value pairs.

This is ~4n in time and ~4n in space, including the final dictionary. It is probably faster than a loop, though, since the zip, dict, and slicing operators are written in C.

like image 186
pavpanchekha Avatar answered Nov 15 '22 21:11

pavpanchekha