python dict.fromkeys
时间: 2023-11-23 19:14:00 浏览: 76
Python中的dict.fromkeys()函数用于创建一个新字典,该字典使用指定的键和可选的默认值来初始化。该函数的语法如下:
dict.fromkeys(seq[, value])
其中,seq是指定的键的序列,可以是一个列表、元组或其他可迭代对象;value是可选的默认值,用于初始化字典中的所有键的值。如果没有指定value,默认值为None。
以下是几个使用dict.fromkeys()函数的示例:
1. 使用默认值初始化字典:
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq)
print("新字典为: %s" % str(dict))
输出结果为:{'Google': None, 'Runoob': None, 'Taobao': None}
2. 使用指定的默认值初始化字典:
seq = ('Google', 'Runoob', 'Taobao')
dict = dict.fromkeys(seq, 10)
print("新字典为: %s" % str(dict))
输出结果为:{'Google': 10, 'Runoob': 10, 'Taobao': 10}
3. 使用元组作为默认值初始化字典:
seq = ('name', 'age', 'class')
dict = dict.fromkeys(seq, ('zs', 8, 'Two'))
print("新字典为: %s" % str(dict))
输出结果为:{'name': ('zs', 8, 'Two'), 'age': ('zs', 8, 'Two'), 'class': ('zs', 8, 'Two')}
通过dict.fromkeys()函数,可以快速生成一个字典,并设置默认值或使用特定的值来初始化字典的键的值。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python 字典(Dictionary) fromkeys()方法](https://blog.csdn.net/weixin_41147796/article/details/118755787)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Python使用dict.fromkeys()快速生成一个字典示例](https://download.csdn.net/download/weixin_38626473/12863433)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [python中dict的fromkeys用法](https://blog.csdn.net/sinat_38682860/article/details/108624415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文