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
If you have an ordered dict, then d. keys(). index(k) should do it.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With