Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.items():
     count += 1
     print key,value, count
like image 574
vkaul11 Avatar asked Jun 06 '13 23:06

vkaul11


People also ask

How do you get the index of an element in a dict in Python?

If you have an ordered dict, then d. keys(). index(k) should do it.

Do dictionary keys have indexes?

The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-value pairs.


1 Answers

You can use the enumerate() function:

for count, (key, value) in enumerate(my_dict.items(), 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.items(), 1):
...     print key, value, count
... 
42 Life, the Universe and Everything 1
foo bar 2
monty python 3
like image 56
Martijn Pieters Avatar answered Oct 07 '22 14:10

Martijn Pieters