Python3 字典
描述
Python 字典 fromkeys() 函數用于創(chuàng)建一個新字典,以序列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}
更多建議: