當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Dictionary fromkeys()用法及代碼示例

字典 fromkeys() 方法

fromkeys() 方法用於創建具有給定鍵和值的字典。

用法:

    dictionary_name.fromkeys(keys, value)

參數:

  • keys– 它代表一個帶有鍵的容器(可迭代)。
  • value– 它是一個可選參數,用於指定值。默認值為None

返回值:

這個方法的返回類型是<class 'dict'>,它返回具有指定鍵和值的新創建的字典。

例:

# Python Dictionary fromkeys() Method with Example

# keys iterbale
keys = ('id', 'age', 'perc')

# value
value = 0

# creating dictionary with keys and value
x = dict.fromkeys(keys, value)

# printing dictionary
print("data of x dictionary...")
print(x)

# creating dictionary with keys only
y = dict.fromkeys(keys)

# printing dictionary
print("data of y dictionary...")
print(y)

輸出

data of x dictionary...
{'perc':0, 'id':0, 'age':0}
data of y dictionary...
{'perc':None, 'id':None, 'age':None}


相關用法


注:本文由純淨天空篩選整理自 Python Dictionary fromkeys() Method with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。