当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。