python - Python 中的 enumerate() 字典

标签 python python-3.x dictionary enumerate

我知道我们使用 enumerate 来迭代列表,但我在字典上尝试过它并没有报错。

代码:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}

for i, key in enumerate(enumm):
    print(i, key)

输出:

0 0

1 1

2 2

3 4

4 5

5 6

6 7

有人可以解释一下输出吗?

最佳答案

除了已经提供的答案之外,Python 中有一个非常好的模式,它允许您枚举字典的键和值。

枚举字典的键的正常情况:

example_dict = {1:'a', 2:'b', 3:'c', 4:'d'}

for i, k in enumerate(example_dict):
    print(i, k)

哪些输出:

0 1
1 2
2 3
3 4

但如果您想同时枚举键和值,方法如下:

for i, (k, v) in enumerate(example_dict.items()):
    print(i, k, v)

哪些输出:

0 1 a
1 2 b
2 3 c
3 4 d

关于python - Python 中的 enumerate() 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36244380/

相关文章:

Python调用和控制台输出问题

c# - Dictionary<> 总是按值排序,从键查找索引

python - 如何使用列表/字典理解在 Python 中获取唯一值

python - 如何循环遍历此 Python 字典并搜索是否存在值

python - 根据包含空值的其他列使用掩码设置值

python - 使用 M2Crypto 加密文件

python - 这个 SciPy 教程指的是什么 python 函数?

python-3.x - OpenCV 4.4.0 : qt. qpa.xcb : could not connect to display on a remote EC2 instance. 如何解决这个问题?

python-3.x - 在discord.py 中嵌入多张照片

python - 发现错误 : Statement expected, py: Dedent