1. 程式人生 > >【Python】Python3 字典 fromkeys()方法

【Python】Python3 字典 fromkeys()方法

描述
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}