Convert a list to a dictionary in Python

Mike picture Mike · Jan 1, 2011 · Viewed 509.4k times · Source

Let's say I have a list a in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value

for example,

a = ['hello','world','1','2']

and I'd like to convert it to a dictionary b, where

b['hello'] = 'world'
b['1'] = '2'

What is the syntactically cleanest way to accomplish this?

Answer

kindall picture kindall · Jan 1, 2011
b = dict(zip(a[::2], a[1::2]))

If a is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.

from itertools import izip
i = iter(a)
b = dict(izip(i, i))

In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with range() and len(), which would normally be a code smell.

b = {a[i]: a[i+1] for i in range(0, len(a), 2)}

So the iter()/izip() method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, zip() is already lazy in Python 3 so you don't need izip().

i = iter(a)
b = dict(zip(i, i))

If you want it on one line, you'll have to cheat and use a semicolon. ;-)