Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect last iteration over dictionary.iteritems() in python

Is there a simple way to detect the last iteration while iterating over a dictionary using iteritems()?

like image 580
kadam Avatar asked May 22 '11 20:05

kadam


People also ask

What is Iteritems () in Python?

The iteritems() method generates an iterator object of the DataFrame, allowing us to iterate each column of the DataFrame. ;0. Note: This method is the same as the items() method. Each iteration produces a label object and a column object. The label is the column name.

How do you iterate over a dictionary key?

In order to iterate over the values of the dictionary, you simply need to call values() method that returns a new view containing dictionary's values.


1 Answers

There is an ugly way to do this:

for i, (k, v) in enumerate(your_dict.iteritems()):
    if i == len(your_dict)-1:
        # do special stuff here

But you should really consider if you need this. I am almost certain that there is another way.

like image 131
Björn Pollex Avatar answered Oct 01 '22 15:10

Björn Pollex