目录

dict.fromkeys()

描述 (Description)

fromkeys()方法创建一个新的字典,其中包含来自seq键和values设置为value。

语法 (Syntax)

以下是fromkeys()方法的语法 -

dict.fromkeys(seq[, value])

参数 (Parameters)

  • seq - 这是用于字典键准备的值列表。

  • value - 这是可选的,如果提供,则value将设置为此值

返回值 (Return Value)

此方法返回列表。

例子 (Example)

以下示例显示了fromkeys()方法的用法。

#!/usr/bin/python
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print "New Dictionary : %s" %  str(dict)
dict = dict.fromkeys(seq, 10)
print "New Dictionary : %s" %  str(dict)

当我们运行上面的程序时,它产生以下结果 -

New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
↑回到顶部↑
WIKI教程 @2018