简体   繁体   中英

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 :

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. In the above example I tell enumerate() to start counting at 1 to match your example; the default is to start at 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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