This fixes issue #246. Previously, this buggy code in python 3, due to it modifying keys of a dictionary being iterated over.