Python – 从列表创建字典
pythonserver side programmingprogramming更新于 2025/10/15 6:04:17
当需要从列表创建字典时,‘dict’中的‘fromkeys’方法方法。
示例
下面是相同的演示 −
my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)
my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)
输出
The list is
['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}
解释
定义一个字符串列表,并显示在控制台上。
‘dict’ 中存在的 ‘fromkeys’ 方法用于将列表的元素转换为字典键。
每个键的值都在此处指定。
这被分配给一个变量。
它作为输出显示在控制台上。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

