Python3 dictionary.fromkeys()方法

2019-10-16 23:10:10
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}