Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Dictionary with List as Keys and Tuple as Values

I have a list that I want to use as the keys to a dictionary and a list of tuples with the values. Consider the following:

d = {}
l = ['a', 'b', 'c', 'd', 'e']
t = [(1, 2, 3, 4), (7, 8, 9, 10), (4, 5, 6, 7), (9, 6, 3, 8), (7, 4, 1, 2)]

for i in range(len(l)):
    d[l[i]] = t[i]

The list will consistently be 5 values and there will consistently be 5 tuples however there are hundreds of thousands of values in each tuple.

My question is this: what is the FASTEST way to populate the dictionary, d, with the tuples in t, with the keys being the values in l?

like image 713
Jason Strimpel Avatar asked May 31 '11 16:05

Jason Strimpel


2 Answers

I did no timings, but probably

d = dict(zip(l, t))

will be quite good. For only 5 key-value pairs, I don't think izip() will provide any advantage over zip(). The fact that each tuple has a lot of items does not matter for this operation, since the tuple objects are not copied at any point, neither with your approach nor with mine. Only pointers to the tuple objects are inserted in the dicitonary.

like image 141
Sven Marnach Avatar answered Oct 06 '22 14:10

Sven Marnach


To build on Sven's answer, using itertools.izip would be faster and use less memory if you needed to create a larger dict. With only five key/value pairs the time to build the dict will be miniscule.

python -m timeit -s "l = l2 = range(100000)" "dict(zip(l, l2))" 
1000 loops, best of 3: 20.1 msec per loop
python -m timeit -s "import itertools; l = l2 = range(100000)" "dict(itertools.izip(l, l2))"
1000 loops, best of 3: 9.59 msec per loop
like image 22
zeekay Avatar answered Oct 06 '22 14:10

zeekay