简体   繁体   English

如何在dict中获取项目索引或数字以及键,值

[英]how to get item index or number along with key,value in dict

For dictionary I want to keep track of number of items that have been parsed. 对于字典,我想跟踪已解析的项目数。 Is there a better way to do that compared to what is shown below? 与下面显示的相比,有更好的方法吗?

count = 0
for key,value in my_dict.iteritems():
     count += 1
     print key,value, count

You can use the enumerate() function : 您可以使用enumerate()函数

for count, (key, value) in enumerate(my_dict.iteritems(), 1):
    print key, value, count

enumerate() efficiently adds a count to the iterator you are looping over. enumerate()有效地向你循环的迭代器添加一个计数。 In the above example I tell enumerate() to start counting at 1 to match your example; 在上面的例子中,我告诉enumerate()1开始计数以匹配你的例子; the default is to start at 0. 默认值是从0开始。

Demo: 演示:

>>> somedict = {'foo': 'bar', 42: 'Life, the Universe and Everything', 'monty': 'python'}
>>> for count, (key, value) in enumerate(somedict.iteritems(), 1):
...     print key, value, count
... 
42 Life, the Universe and Everything 1
foo bar 2
monty python 3

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

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