Best way to convert a list to a dictionary

Peter Schneider-Kamp petersc at stud.ntnu.no
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
code:

import time # for the timing

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

# list initialization
list=[]
for i in range(100000):
  list.append([i,i+1])

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

# map version
t = time.time()
dict = {}
map(dodictmap,list)
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.

Bye
Peter
--
Peter Schneider-Kamp          ++47-7388-7331
Herman Krags veg 51-11        mailto:peter at schneider-kamp.de
N-7050 Trondheim              http://schneider-kamp.de




More information about the Python-list mailing list