Create dict from two lists

Xavier Morel xavier.morel at masklinn.net
Fri Feb 10 09:15:04 EST 2006


Diez B. Roggisch wrote:
> py wrote:
> 
>> I have two lists which I want to use to create a dictionary.  List x
>> would be the keys, and list y is the values.
>>
>> x = [1,2,3,4,5]
>> y = ['a','b','c','d','e']
>>
>> Any suggestions?  looking for an efficent simple way to do this...maybe
>> i am just having a brain fart...i feel like this is quit simple.
> 
> dict(zip(x,y))
> 
> Diez
I'd even suggest using izip (from itertools), it's often much faster 
than zip (end result is the same).

Demo:

 >>> from itertools import izip
 >>> l1 = range(5000)
 >>> l2 = range(5000, 10000)
 >>> from timeit import Timer
 >>> t1 = Timer("dict(zip(l1, l2))", "from __main__ import l1, l2")
 >>> t2 = Timer("dict(izip(l1, l2))", "from __main__ import l1, l2, izip")
 >>> min(t1.repeat(5, 10000))
17.989041903370406
 >>> min(t2.repeat(5, 10000))
10.381146486494799
 >>>

42% speed gain from using izip instead of zip (memory was not an issue 
during the test, machine had 1.3Gb of available ram)



More information about the Python-list mailing list