Im looping though a dictionary using
for key, value in mydict.items():
And I wondered if theres some pythonic way to also access the loop index / iteration number. Access the index while still maintaining access to the key value information.
for key, value, index in mydict.items():
its is because I need to detect the first time the loop runs. So inside I can have something like
if index != 1:
To check the index in for loop you can use enumerate() function. In Python, the enumerate() is an in-built function that allows us to loop over a list and count the number of elements during an iteration with for loop.
There are two ways of iterating through a Python dictionary object. One is to fetch associated value for each key in keys() list. There is also items() method of dictionary object which returns list of tuples, each tuple having key and value.
Iterate over all key-value pairs of dictionary by index As we passed the sequence returned by items() to the enumerate() function with start index 0 (default value). Therefore it yielded each item (key-value) of dictionary along with index, starting from 0.
You can use enumerate
function, like this
for index, (key, value) in enumerate(mydict.items()):
print index, key, value
The enumerate
function gives the current index of the item and the actual item itself. In this case, the second value is actually a tuple of key and value. So, we explicitly group them as a tuple, during the unpacking.
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