6

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?

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

2 Comments

These timings use a lot more than 5 key-value pairs, so I'm not surprised about the difference. For only 5 key-value pairs, the difference will be immaterial. (BTW, +1 for actually measuring instead of guessing!)
@Sven That's a good point. With only 5 key-value pairs, speed will be minuscule either way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.