从列表填充字典的最快方法?

时间:2018-09-04 10:58:07

标签: python python-3.x list dictionary

这是我的清单:

animallist=["bird","cow","chicken","horse"]

我想创建一个词典,用这些动物作为键和由some_funtion确定的值。我的脚本:

def some_function(eachanimal):
    #do some stuff with the entry, for example:
    return eachanimal+"_value"

animallist=["bird","cow","chicken","horse"]
mydict={}
for eachanimal in animallist:
    mydict[eachanimal]=some_function(eachanimal)

这将创建mydict,即:

{'bird': 'bird_value',
'cow': 'cow_value',
'chicken': 'chicken_value',
'horse': 'horse_value'}

如何更快或更紧凑地执行此操作?

5 个答案:

答案 0 :(得分:2)

我可以肯定它不会更快,但是我发现它至少更优雅

mydict = {x: some_function(x) for x in animallist}

答案 1 :(得分:1)

您可以使用dict-comprehension使其更紧凑:

dct = {animal: animal+"_value" for animal in animallist}

答案 2 :(得分:1)

要使其更紧凑,请使用dict理解-

{eachanimal:some_function(eachanimal) for eachanimal in animallist}

使用timeit为时间码位-

In [1]: s = """\
    ...: animallist=["bird","cow","chicken","horse"]
    ...: def some_function(eachanimal):
    ...:     return eachanimal+"_value"
    ...: animallist=["bird","cow","chicken","horse"]
    ...: mydict={}
    ...: for eachanimal in animallist:
    ...:     mydict[eachanimal]=some_function(eachanimal)
    ...: """

In [2]: min(timeit.repeat(s, repeat=5))
Out[3]: 0.9832079410552979

In [4]: s = """\
    ...: animallist=["bird","cow","chicken","horse"]
    ...: dict((eachanimal,eachanimal+'_value') for eachanimal in animallist)
    ...: """

In [5]: min(timeit.repeat(s, repeat=5))
Out[6]: 1.5261759757995605

In [7]: s = """\
    ...: animallist=["bird","cow","chicken","horse"]
    ...: def some_function(eachanimal):
    ...:     return eachanimal+"_value"
    ...: {eachanimal:some_function(eachanimal) for eachanimal in animallist}
    ...: """

In [8]: min(timeit.repeat(s, repeat=5))
Out[9]: 1.1118130683898926

In [10]: s = """\
    ...: animallist=["bird","cow","chicken","horse"]
    ...: dict(zip(animallist,[s + "_value" for s in animallist]))
    ...: """

In [11]: min(timeit.repeat(s, repeat=5))
Out[12]: 1.603926181793213

In [13]: s = """\
    ...: animallist=["bird","cow","chicken","horse"]
    ...: {eachanimal:eachanimal+'_value' for eachanimal in animallist}
    ...: """

In [14]: min(timeit.repeat(s, repeat=5))
Out[15]: 0.6992459297180176

在我的系统i5-3437U CPU @ 1.90GHz, 8GB RAM上,它看起来像

{eachanimal:eachanimal+'_value' for eachanimal in animallist}

实际上比您的版本更快

答案 3 :(得分:1)

animallist=["bird","cow","chicken","horse"]
dict(zip(animallist,[s + "_value" for s in animallist]))

但是我喜欢Rakesh的答案!

答案 4 :(得分:1)

使用dict

例如:

animallist=["bird","cow","chicken","horse"]
print( dict((i, i+"_value") for i in animallist) )

输出:

{'chicken': 'chicken_value', 'horse': 'horse_value', 'bird': 'bird_value', 'cow': 'cow_value'}