有没有更好的方法来创建字典哪些键来自列表并且值是常见的?
输入:记录UID列表和项目名称。
输出:记录UID和项目名称字典词典。
我当前的代码:
>>> doc_uid = [u'AAAB3086', u'AAAB3085']
>>> project_name = "Custom Project One"
>>> doc_project_map = {}
>>> for ii in doc_uid:
... doc_project_map[ii] = project_name
...
>>> doc_project_map
{u'AAAB3086': 'Custom Project One', u'AAAB3085': 'Custom Project One'}
>>>
为什么我这样做是因为在下一个过程中我有所有的文档UID,我必须找到它的项目名称。
项目很多,每个项目都包含很多文档。
Actaul Algo是:
像:
doc_project_map = {}
for project_onj in project_objes:
project_name = getProjectName(project_obj)
docuents_uids = getProjectDcoumentUID(project_obj)
for docuents_uid in docuents_uids:
doc_project_map[docuents_uid] = project_name
答案 0 :(得分:2)
dict(zip(doc_uid,len(doc_uid)*[project_name]))
答案 1 :(得分:1)
from itertools import repeat, izip
d = dict(izip(doc_uid,repeat(project_name)))
或者使用fromkeys,因为你的值是不可变的:
d = dict.fromkeys(doc_uid,project_name)
fromkeys是使用python2最有效的方法:
In [28]: doc_uid = range(100000)
In [29]: timeit dict(izip(doc_uid,repeat(project_name)))
100 loops, best of 3: 6.16 ms per loop
In [30]: timeit dict.fromkeys(doc_uid,project_name)
100 loops, best of 3: 5.16 ms per loop
In [31]: timeit dict(izip(doc_uid,len(doc_uid)*[project_name]))
100 loops, best of 3: 7.19 ms per loop
In [32]: timeit {k:project_name for k in doc_uid}
100 loops, best of 3: 7.22 ms per loop
使用python 3的相同顺序:
In [7]: timeit dict(zip(doc_uid,len(doc_uid)*[project_name]))
100 loops, best of 3: 13.1 ms per loop
In [8]: timeit dict.fromkeys(doc_uid,project_name)
100 loops, best of 3: 10.3 ms per loop
In [9]: timeit dict(zip(doc_uid,repeat(project_name)))
100 loops, best of 3: 11.7 ms per loop
In [10]: timeit {k:project_name for k in doc_uid}
100 loops, best of 3: 13.3 ms per loop