Python 中以索引作为值的字典
pythonserver side programmingprogramming更新于 2025/11/23 16:12:17
在本文中,我们将学习如何从另一个常用的 Python 集合(即列表)创建字典。索引或键不是列表内容的一部分。但在字典中,我们需要将键或索引附加到每个元素上,这些元素称为值。
使用枚举
枚举函数将计数器添加为枚举对象的键。因此,我们将其应用于给定的列表并使用 for 循环。这将创建所需的字典,其中的键由枚举函数生成。
示例
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11]
# 给定列表
print("给定列表:" , Alist)
# 转换为字典
NewDict = {val: key + 1 for key, val in enumerate(Alist)}
# 打印结果
print("Dictionary created with index : ",NewDict)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
请注意,当存在重复元素时,仅显示重复元素中索引值较高的元素。
使用 zip 和 range
另一种方法是应用 range 函数来创建键,从 1 开始,直到提供的列表的长度。最后,我们应用 dict 函数来创建字典。
示例
Alist = ['Mon', 'Tue', 'Wed', 'Wed',11,11]
# 给定列表
print("Given list : " , Alist)
# Converting to DIctionary
NewDict = dict(zip(Alist, range(1, len(Alist)+1)))
# 打印结果
print("Dictionary created with index : ",NewDict)
输出
运行上述代码得到以下结果 −
Given list : ['Mon', 'Tue', 'Wed', 'Wed', 11, 11]
Dictionary created with index : {'Mon': 1, 'Tue': 2, 'Wed': 4, 11: 6}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

