removing dictionary entries with no values- Python

.keys() provides access to the list of keys in the dictionary, but changes to it are not (necessarily) reflected in the dictionary. You need to use del dictionary[key] or dictionary.pop(key) to remove it.

Because of the behaviour in some version of Python, you need to create a of copy of the list of your keys for things to work right. So your code would work if written as:

for x in list(dict2.keys()):
    if dict2[x] == []:
        del dict2[x]

Newer versions of python support dict comprehensions:

dic = {i:j for i,j in dic.items() if j != []}

These are much more readable than filter or for loops


for x in dict2.keys():
    if dict2[x] == []:
        del dict2[x]