Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python loop index of key, value for-loop when using items()

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:
like image 354
binarysmacker Avatar asked Aug 06 '14 00:08

binarysmacker


People also ask

How do you find the index of an item in a for loop?

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.

How do you iterate keys and values in Python?

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.

How do you iterate over an index in a dictionary?

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.


1 Answers

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.

like image 171
thefourtheye Avatar answered Oct 25 '22 22:10

thefourtheye