Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

james wells
james wells
5,029 Points

Iterating through a Dictionary in Python (StopIteration Error)

How do you iterate through a dictionary in python without the StopIteration Error? I created a list of events inside a dictionary that are assigned a time. I use a timer to check against that time and if the time of the event matches the timer, the event happens. This works fine until you reach the last event. Once you reach the last event in the dictionary, the event doesnt play and I get a StopIteration error because I have reached the end of the dictionary of events.

Prior to While loop

enemy_spawn_timer = pygame.time.get_ticks()
    event_dict = {"enemy1":3000, "enemy2":9000,"enemy3":5000, "END": 1000}
    next_event_key = next(iter(event_dict))

Inside of While loop

if pygame.time.get_ticks() > enemy_spawn_timer + event_dict[next_event_key]:
            enemy_spawn_timer = pygame.time.get_ticks()
            enemy = Enemy()
            enemy.rect.x = 518  # place offscreen
            enemy.rect.y = random.randrange(40, 184)  # account for the terrain
            enemy_list.add(enemy)
            del event_dict[next_event_key]
            next_event_key = next(iter(event_dict,))
            #if next_event_key == event_dict["END"]:
                #raise StopIteration 

The last two lines were an attempt to stop the iteration without an error but didnt work.

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,720 Points

So you figured out that next() function returns the next item in an iterator. Nice work.

You can add a default return value in next() as the second parameter, to return if the iterable has reached its end.

Syntax

next(iterable, default)

I hope that helps.