Bugfix in clear_cache

You cannot delete keys while traversing through a dictionary. Moved key
deletion to second iteration.