如何在1行代码中不使用for循环创建字典?

Jak*_*lan 2 python dictionary

这是我的代码:

dictionary = {}
for i in range(2, 15):
    dictionary[str(i)] = 0
Run Code Online (Sandbox Code Playgroud)

是否可以用一行代码创建它?

U10*_*ard 7

使用:

print(dict.fromkeys(range(2,15),0))
Run Code Online (Sandbox Code Playgroud)

或者如果想要字典键的字符串:

print(dict.fromkeys(map(str,range(2,15)),0))
Run Code Online (Sandbox Code Playgroud)

或者另一种制作键字符串的方法:

print(dict.fromkeys([str(i) for i in range(2,15)],0))
Run Code Online (Sandbox Code Playgroud)


L3v*_*han 5

是:

dictionary = {str(i): 0 for i in range(2, 15)}
Run Code Online (Sandbox Code Playgroud)

这称为字典理解.列表,生成器和集合有类似的语法结构.