enumerate() 用于 Python 中的字典

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36244380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:37:15  来源:igfitidea点击:

enumerate() for dictionary in python

pythonpython-3.xdictionaryenumerate

提问by Aditya Krishn

I know we use enumeratefor iterating a list but I tried it in a dictionary and it didn't give an error.

我知道我们enumerate用于迭代列表,但我在字典中尝试过它并没有给出错误。

CODE:

代码:

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

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

OUTPUT:

输出:

0 0

1 1

2 2

3 4

4 5

5 6

6 7

Can someone explain the output?

有人可以解释输出吗?

回答by Jo?o Almeida

On top of the already provided answers there is a very nice pattern in Python that allows you to enumerate both keys and values of a dictionary.

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

The normal case you enumerate the keysof the dictionary:

枚举字典的正常情况:

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

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

Which outputs:

哪些输出:

0 1
1 2
2 3
3 4

But if you want to enumerate through both keys and valuesthis is the way:

但是,如果您想枚举键和值,则可以这样做:

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

Which outputs:

哪些输出:

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

回答by Aditya Krishn

The first column of output is the index of each item in enummand the second one is its keys. If you want to iterate your dictionary then use .items():

输出的第一列是每个项目的索引,enumm第二列是它的键。如果你想迭代你的字典,那么使用 .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

输出应如下所示:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7

回答by Jordan Mackie

Just thought I'd add, if you'd like to enumerate over the index, key, and values of a dictionary, your for loop should look like this:

只是想补充一下,如果您想枚举字典的索引、键和值,您的 for 循环应如下所示:

for index, (key, value) in enumerate(your_dict.items()):
    print(index, key, value)

回答by roadrunner66

for k,v in dict.iteritems():
    print(k,v)

回答by Ankur Ranjan

Since you are using enumeratehence your iis actually the index of the key rather than the key itself.

由于您正在使用,enumerate因此您i实际上是键的索引而不是键本身。

So, you are getting 3in the first column of the row 3 4even though there is no key 3.

因此,即使没有 key ,您也会进入3该行的第一列。3 43

enumerateiterates through a data structure(be it list or a dictionary) while also providing the current iteration number.

enumerate遍历数据结构(无论是列表还是字典),同时还提供当前的迭代次数。

Hence, the columns here are the iteration number followed by the key in dictionary enum

因此,这里的列是迭代次数,后跟字典中的键 enum

Others Solutions have already shown how to iterate over key and value pair so I won't repeat the same in mine.

其他解决方案已经展示了如何迭代键和值对,所以我不会在我的中重复相同的内容。

回答by Abhishek Roy

enumerate()when working on list actually gives the index and the value of the items inside the list. For example:

enumerate()在处理列表时,实际上给出了列表中项目的索引和值。例如:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for i, j in enumerate(list):
    print(i, j)

gives

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9

where the first column denotes the index of the item and 2nd column denotes the items itself.

其中第一列表示项目的索引,第二列表示项目本身。

In a dictionary

在字典里

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, j in enumerate(enumm):
    print(i, j)

it gives the output

它给出了输出

0 0
1 1
2 2
3 4
4 5
5 6
6 7

where the first column gives the index of the key:valuepairs and the second column denotes the keysof the dictionary enumm.

其中第一列给出对的索引,key:value第二列表示keys字典的索引enumm

So if you want the first column to be the keysand second columns as values, better try out dict.iteritems()(Python 2)or dict.items()(Python 3)

因此,如果您希望第一列成为keys第二列values,最好尝试dict.iteritems()(Python 2)dict.items()(Python 3)

for i, j in enumm.items():
    print(i, j)

output

输出

0 1
1 2
2 3
4 4
5 5
6 6
7 7

Voila

回答by Kostiantyn Medvid

Python3:

蟒蛇3:

One solution:

一种解决方案:

enumm = {0: 1, 1: 2, 2: 3, 4: 4, 5: 5, 6: 6, 7: 7}
for i, k in enumerate(enumm):
    print("{}) d.key={}, d.value={}".format(i, k, enumm[k]))


Output:
0) enumm.key=0, enumm.value=1
1) enumm.key=1, enumm.value=2
2) enumm.key=2, enumm.value=3
3) enumm.key=4, enumm.value=4
4) enumm.key=5, enumm.value=5
5) enumm.key=6, enumm.value=6
6) enumm.key=7, enumm.value=7

An another example:

另一个例子:

d = {1 : {'a': 1, 'b' : 2, 'c' : 3},
     2 : {'a': 10, 'b' : 20, 'c' : 30}
    }    
for i, k in enumerate(d):
        print("{}) key={}, value={}".format(i, k, d[k])


Output:    
    0) key=1, value={'a': 1, 'b': 2, 'c': 3}
    1) key=2, value={'a': 10, 'b': 20, 'c': 30}

回答by wp-overwatch.com

That sure must seem confusing. So this is what is going on. The first value of enumerate (in this case i) returns the next index value starting at 0 so 0, 1, 2, 3, ... It will always return these numbers regardless of what is in the dictionary. The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). What you really want to do is what roadrunner66 responded with.

这肯定看起来令人困惑。所以这就是正在发生的事情。enumerate 的第一个值(在本例中为 i)返回从 0 开始的下一个索引值,所以 0, 1, 2, 3, ... 无论字典中有什么,它都会返回这些数字。enumerate 的第二个值(在本例中为 j)返回字典/枚举中的值(我们在 Python 中称之为字典)。你真正想做的是 roadrunner66 的回应。

回答by VPfB

  1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
  2. The order of the keys is determined by the implementation code and you cannot expect some specific order:

    Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

  1. 迭代 Python dict 意味着以与使用完全相同的方式迭代其键 dict.keys()
  2. 键的顺序由实现代码决定,您不能指望某些特定的顺序:

    键和值以任意顺序迭代,该顺序是非随机的,因 Python 实现而异,并取决于字典的插入和删除历史。如果在没有对字典进行干预的情况下迭代键、值和项目视图,项目的顺序将直接对应。

That's why you see the indices 0 to 7 in the first column. They are produced by enumerateand are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.

这就是您在第一列中看到索引 0 到 7 的原因。它们是由生产的,enumerate并且总是以正确的顺序排列。此外,您会在第二列中看到 dict 的键 0 到 7。它们没有排序。

回答by user3358337

d = {0: 'zero', '0': 'ZERO', 1: 'one', '1': 'ONE'}

print("List of enumerated d= ", list(enumerate(d.items())))

output:

输出:

List of enumerated d=  [(0, (0, 'zero')), (1, ('0', 'ZERO')), (2, (1, 'one')), (3, ('1', 'ONE'))]