Python 字典(Dictionary) fromkeys()方法
描述
Python 字典(Dictionary) fromkeys() 函數用於創建一個新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對應的初始值。
語法
fromkeys()方法語法:
dict.fromkeys(seq[, value]))
參數
- seq -- 字典鍵值列表。
- value -- 可選參數, 設置鍵序列(seq)的值。
返回值
該方法返回列表。
實例
以下實例展示了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}