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

这是我的清单:


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

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


临摹微笑
浏览 176回答 3
3回答

子衿沉夜

我很确定它不会更快,但我发现它至少更优雅mydict = {x: some_function(x) for x in animallist}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python