开发者

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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜