Jas*_*pel 6 python dictionary tuples list
我有一个列表,我想用作字典的键和带有值的元组列表.考虑以下:
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]
Run Code Online (Sandbox Code Playgroud)
该列表将始终为5个值,并且将始终为5个元组,但每个元组中有数十万个值.
我的问题是:用t中的元组填充字典d的最快方法是什么,键是l中的值?
Sve*_*ach 17
我没有时间,但可能
d = dict(zip(l, t))
Run Code Online (Sandbox Code Playgroud)
会很好的.对于只有5个键值对,我认为izip()不会提供任何优势zip().每个元组都有很多项目的事实对于这个操作无关紧要,因为元组对象不会在任何时候被复制,既不是你的方法也不是我的.只有指向元组对象的指针才会插入到dicitonary中.
基于Sven的答案,itertools.izip如果你需要创建一个更大的dict ,使用会更快并且使用更少的内存.只有五个键/值对,构建字典的时间将是微不足道的.
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
Run Code Online (Sandbox Code Playgroud)