Fix "dictionary changed size during iteration" in python 3