Best way to convert a list to a dictionary

Peter Schneider-Kamp petersc at
Thu May 4 08:22:03 CEST 2000

Michael Husmann wrote:
> d = {}
> for k, v in your_list:
>     d[k] = v
> This example looks nice bus does not work with my Python 1.52. Trying to
> get both elements from 'your_list' produces a TypeError exception:

Thats rather strange. I used exactly that code to benchmark it against
a reduce-based solution. It works flawlessly on my 1.5.2. Here is the

import time # for the timing

# helper functions assuming dict is the
# dictionary to use
def dodictreduce(a,b):
  return b
def dodictmap(a):

# list initialization
for i in range(100000):

# reduce version
t = time.time()
k,v = reduce(dodictreduce,list)
dict[k] = v
t = time.time() - t
print t

# map version
t = time.time()
dict = {}
t = time.time() - t
print t

# for-loop version
t = time.time()
dict = {}
for key, value in list:
    dict[key] = value
t = time.time() - t
print t

# yet-another-for-loop version
t = time.time()
dict = {}
for a in list:
    dict[a[0]] = a[1]
t = time.time() - t
print t

By the way: The direct for-loop version proposed 
is asymptotically about 5% faster than the reduce
version and about 15% faster than the map version
on my machine. It performs just very slightly
faster than the other for loop.
So as far as I can see the direct for-loop is the
thing to go after.

Peter Schneider-Kamp          ++47-7388-7331
Herman Krags veg 51-11        mailto:peter at
N-7050 Trondheim    

More information about the Python-list mailing list