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

Im loop though dictionary using

for key, value in mydict.items(): 

And I was wondering if any pythonic way also has access to the loop / iteration number of the loop. Get access to the index, while maintaining access to information about the key value.

 for key, value, index in mydict.items(): 

this is because I need to detect the first cycle of the cycle. So inside I can have something like

 if index != 1: 
+8
python dictionary
source share
3 answers

You can use enumerate like this

 for index, (key, value) in enumerate(mydict.items()): print index, key, value 

The enumerate function gives the current index of the element and the actual element itself. In this case, the second value is actually a tuple of key and value. Thus, we explicitly group them as a tuple during unpacking.

+24
source share

If you only need an index to do something special in the first iteration, you can also use .popitem()

 key, val = mydict.popitem() ... for key, val in mydict.items() ... 

this will remove the first key, val pair from mydict (but maybe this is not a problem for you?)

+1
source share
 if mydict: iterdict = mydict.iteritems() firstkey, firstvalue = next(iterdict) # do something special with first item for key, value in iterdict: # do something with the rest 
0
source share

All Articles