Python3 dictionary.fromkeys()方法

fromkeys()方法使用seq的值作为键,来设置创建新的字典。

语法

下面是 fromkeys()方法的语法 -
dict.fromkeys(seq[, value]))

参数

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

  • value -- 这是可选的,如果提供的话则这个值将被设置为字典的值

返回值

此方法返回列表。

示例

下面的例子显示fromkeys()方法的使用。
#!/usr/bin/python3

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}

上一篇: Python3元组 下一篇: Python3字典