首页 > 解决方案 > 从列表中填充字典的最快方法?

问题描述

这是我的清单:

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'}

我怎样才能更快或更紧凑地做到这一点?

标签: pythonpython-3.xlistdictionary

解决方案


我很确定它不会更快,但我发现它至少更优雅

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

推荐阅读