在 for 循环中初始化 dict 的 pythonic 方式

Ali*_*ina 2 python dictionary

python 有没有初始化字典的方法?

animals = ["dog","cat","cow"]
for x in animals:
    primers_pos[x]={}
Run Code Online (Sandbox Code Playgroud)

有没有类似的东西

(primers_pos[x]={} for x in animals)
Run Code Online (Sandbox Code Playgroud)

Eug*_*ash 7

您可以使用字典理解(Python 2.7+ 支持):

>>> animals = ["dog", "cat", "cow"]
>>> {x: {} for x in animals}
{'dog': {}, 'cow': {}, 'cat': {}}
Run Code Online (Sandbox Code Playgroud)