【Python】Python3 字典 fromkeys()方法
阿新 • • 發佈:2019-02-05
描述
Python字典fromkeys()
函式用於建立一個新字典,以序列seq
中元素做字典的鍵,value
為字典所有鍵對應的初始值。
語法
fromkeys()
方法語法:
dict.fromkeys(seq[, value]))
引數
- seq–字典鍵值列表。
- value–可選引數, 設定鍵序列(
seq
)的值。
返回值
該方法返回列表。
例項
以下例項展示了fromkeys()
函式的使用方法:
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("新的字典為 : %s" % str(dict))
新的字典為 : {'name' : None, 'age': None, 'sex': None}
seq = ('name', 'age', 'sex')
dict = dict.fromkeys(seq)
print ("新的字典為 : %s" % str(dict))
新的字典為 : {'name': 10, 'age': 10, 'sex': 10}