Python3 字典fromkeys()方法
描述
Python 字典fromkeys() 函數用於創建一個新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對應的初始值。
語法
fromkeys()方法語法:
dict.fromkeys(seq[, value]))
參數
- seq -- 字典鍵值列表。
- value -- 可選參數, 設置鍵序列(seq)的值。
返回值
該方法返回列表。
實例
以下實例展示了fromkeys()函數的使用方法:
#!/usr/bin/python3 seq = ('name', 'age', 'sex') dict = dict.fromkeys(seq) print ("新的字典为 : %s" % str(dict)) dict = dict.fromkeys(seq, 10) print ("新的字典为 : %s" % str(dict))
以上實例輸出結果為:
新的字典为 : {'age': None, 'name': None, 'sex': None} 新的字典为 : {'age': 10, 'name': 10, 'sex': 10}