.keys() provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. To delete it, use del dictionary[key] or dictionary.pop(key) .
Due to the behavior in some version of Python, you need to create a copy of your keys list so that everything can work correctly. Thus, your code will work if it is written as:
for x in list(dict2.keys()): if dict2[x] == []: del dict2[x]
Jeremy banks
source share