how to get item index or number along with key,value in dict
Solution 1:
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