Python语言基础
Python语言进阶
Python数据结构

Python dictionary fromkeys() 方法

搞懂Python dictionary fromkeys() 方法的用法

描述

Python 字典 fromkeys() 函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。

语法

fromkeys() 方法语法:
dict.fromkeys(seq[, value])

参数

seq -- 字典键值列表。 value -- 可选参数, 设置键序列(seq)对应的值,默认为 None。

返回值

该方法返回一个新字典。

实例

以下实例展示了 fromkeys()函数的使用方法:
seq = ('name' , ' age' , 'sex')
dict = dict . fromkeys ( seq )
print ("新的字典为 : %s "% str (dict))
dict = dict . fromkeys ( seq , 10 )
print ("新的字典为 : %s " % str (dict))
以上实例输出结果为:
新的字典为 : {'name': None, ' age': None, 'sex': None}
新的字典为 : {'name': 10, ' age': 10, 'sex': 10}
不指定值:
x = ('key1' , 'key2' , 'key3' )
dict1 = dict.fromkeys(x)
print(dict1)
以上实例输出结果为:
{'key1': None, 'key2': None, 'key3': None}
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4