方法dict.fromkeys() 是一个非常有用的方法,它可以从一个给定的键的迭代器中创建新的字典。
定义:dict.fromkeys() 是一个方法,它输入键和可能的可选值,并输出一个带有指定键的字典 ,这些键被映射到可选的指定值或默认的None 值。
dict.fromkeys() 语法
方法声明
dict.fromKeys(keys, optional_value)
Parameter Arguments:
keys | 必要的输入 | Iterable 输入,指定新制作的 dictionary 的键。 |
optional_value | optional input | 指定分配给 dictionary 中每个键的值,默认的可选值是None 。 |
dict.fromkeys() 方法的例子
接下来,我们要研究dict.fromkeys() 方法的三个例子。
例子 1
下面是一个有序整数字典的例子,有和没有可选值。
# Initializing a number sequence:
sequence = {1, 2, 3, 4, 5}
# Use the dict.fromKeys() method to convert the sequence to a dictionary:
# Initializing with default None value:
result_dict = dict.fromkeys(sequence)
print('newly made dictionary with default None values: ', result_dict)
# Initializing another dictionary, with an optional value, 1 in this case:
result_dict2 = dict.fromkeys(sequence, 1)
print('2nd dictionary with 1 as the specified value: ', result_dict2)
这是前面代码片断的输出。
newly made dictionary with default None values: {1: None, 2: None, 3: None, 4: None, 5: None}
2nd dictionary with 1 as the specified value: {1: 1, 2: 1, 3: 1, 4: 1, 5: 1}
例2
下面是一个添加指定默认值的例子。
a = ('key_1', 'key_2', 'key_3')
b = 7
default_dict = dict.fromkeys(a, b)
print(default_dict)
# {'key_1': 7, 'key_2': 7, 'key_3': 7}
例3
下面是一个将一个空的字典{} 设置为默认值的例子,dict.fromKeys() 方法。
new_dict = dict.fromkeys(range(5), {})
print('a new dictionary with empty dictionaries as values: ', new_dict)
# a new dictionary with empty dictionaries as values: {0: {}, 1: {}, 2: {}, 3: {}, 4: {}}