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}