3/25/2016 - 12:06 AM

Efficient Dictionary Loops From:

Calling "my_dict.items()" requires generating the entire list of key-value pairs in-memory. Sometimes, if your dictionary is too large, this can be a severe performance bottleneck. To get around this problem we can create a generator via the “iteritems()” method.

A generator allows you to iterate one item at a time. Only the key and value are pulled into memory for every iteration and immediately discarded. There are methods for returning a key generator and value generator as well.

for key, value in my_dict.iteritems():
    print key, value
for key in my_dict.iterkeys():
    print key
for value in my_dict.itervalues():
    print value

Note that one thing you can’t do with a generator is to delete a key during the generator loop.

for x, y in mydictionary:
    del mydictionary[x] 
    # Out: RuntimeError: dictionary changed size during iteration