简体   繁体   English

enumerate() 用于 Python 中的字典

[英]enumerate() for dictionary in python

I know we use enumerate for 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?有人可以解释输出吗?

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 keys of 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 values this 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

The first column of output is the index of each item in enumm and the second one is its keys.输出的第一列是enumm中每个项目的索引,第二列是它的键。 If you want to iterate your dictionary then use .items():如果你想迭代你的字典,那么使用 .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

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)
dict1={'a':1, 'b':'banana'}

To list the dictionary in Python 2.x:要在 Python 2.x 中列出字典:

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

In Python 3.x use:在 Python 3.x 中使用:

for k,v in dict1.items():
        print(k,v)
# a 1
# b banana

Finally, as others have indicated, if you want a running index, you can have that too:最后,正如其他人所指出的,如果你想要一个正在运行的索引,你也可以拥有它:

for i  in enumerate(dict1.items()):
   print(i)  

 # (0, ('a', 1))
 # (1, ('b', 'banana'))

But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up.但这违背了字典 (map, associative array)的目的,字典是一种用于电话簿式查找的有效数据结构。 Dictionary ordering could be incidental to the implementation and should not be relied upon.字典排序可能是实现的附带条件,不应依赖。 If you need the order, use OrderedDict instead.如果您需要订单,请改用OrderedDict

Since you are using enumerate hence your i is actually the index of the key rather than the key itself.由于您使用的是enumerate因此您的i实际上是键的索引而不是键本身。

So, you are getting 3 in the first column of the row 3 4 even though there is no key 3 .所以,你得到3在该行的第一列3 4 ,即使没有钥匙3

enumerate iterates 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.其他解决方案已经展示了如何迭代键和值对,所以我不会在我的中重复相同的内容。

enumerate() when working on list actually gives the index and the value of the items inside the list. enumerate()在处理列表时实际上给出了列表中项目的索引和值。 For example:例如:

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:value pairs and the second column denotes the keys of the dictionary enumm .其中第一列给出key:value对的索引,第二列表示字典enummkeys

So if you want the first column to be the keys and 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

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. enumerate 的第一个值(在本例中为 i)返回从 0 开始的下一个索引值,所以 0, 1, 2, 3, ... 无论字典中有什么,它都会返回这些数字。 The second value of enumerate (in this case j) is returning the values in your dictionary/enumm (we call it a dictionary in Python). enumerate 的第二个值(在本例中为 j)返回字典/枚举中的值(我们在 Python 中称之为字典)。 What you really want to do is what roadrunner66 responded with.你真正想做的是 roadrunner66 的回应。

  1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()迭代 Python dict 意味着以与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.键和值以任意顺序迭代,该顺序是非随机的,因 Python 实现而异,并取决于字典的插入和删除历史。 If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.如果在没有对字典进行干预的情况下迭代键、值和项目视图,项目的顺序将直接对应。

That's why you see the indices 0 to 7 in the first column.这就是您在第一列中看到索引 0 到 7 的原因。 They are produced by enumerate and are always in the correct order.它们由enumerate产生并且总是以正确的顺序排列。 Further you see the dict's keys 0 to 7 in the second column.此外,您会在第二列中看到 dict 的键 0 到 7。 They are not sorted.它们没有排序。

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}

You may find it useful to include index inside key:您可能会发现在键中包含索引很有用:

d = {'a': 1, 'b': 2}
d = {(i, k): v for i, (k, v) in enumerate(d.items())}

Output:输出:

{(0, 'a'): True, (1, 'b'): False}
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'))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM