当前位置:主页 > 软件编程 > Python代码 >

在Python中操作字典之fromkeys()方法的使用

时间:2022-02-11 10:02:03 | 栏目:Python代码 | 点击:

 fromkeys()方法从序列键和值设置为value来创建一个新的字典。
语法

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

dict.fromkeys(seq[, value]))

参数

返回值

此方法返回列表。
例子

下面的例子显示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}

您可能感兴趣的文章:

相关文章