dict
fromkeys()
Python字典fromkeys()方法用于创建一个新的字典,其中包含seq的值和设置为value的值。 语法 以下是fromkeys()方法的语法 - dict.fromkeys(seq[, value]))
Python 参数
- 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))
Python当运行上面的程序,它产生以下结果
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}