Python3 字典 Python3 字典


描述

Python 字典 fromkeys() 函數(shù)用于創(chuàng)建一個(gè)新字典,以序列seq中元素做字典的鍵,value為字典所有鍵對(duì)應(yīng)的初始值。

語(yǔ)法

fromkeys()方法語(yǔ)法:

dict.fromkeys(seq[, value]))

參數(shù)

  • seq -- 字典鍵值列表。
  • value -- 可選參數(shù), 設(shè)置鍵序列(seq)的值。

返回值

該方法返回列表。

實(shí)例

以下實(shí)例展示了 fromkeys()函數(shù)的使用方法:

#!/usr/bin/python3

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print ("新的字典為 : %s" %  str(dict))

dict = dict.fromkeys(seq, 10)
print ("新的字典為 : %s" %  str(dict))

以上實(shí)例輸出結(jié)果為:

新的字典為 : {'age': None, 'name': None, 'sex': None}
新的字典為 : {'age': 10, 'name': 10, 'sex': 10}

Python3 字典 Python3 字典