If I have a dictionary, and I want to remove the entries in which the value is an empty list [] how would I go about doing that?
I tried:
for x in dict2.keys():
if dict2[x] == []:
dict2.keys().remove(x)
but that didn't work.
.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]
.keys(). (Python 2 automatically creates a list, I believe.)for x in dict2.keys():
if dict2[x] == []:
del dict2[x]
def dict_without_empty_values(d):
return {k:v for k,v in d.iteritems() if v}
# Ex;
dict1 = {
'Q': 1,
'P': 0,
'S': None,
'R': 0,
'T': '',
'W': [],
'V': {},
'Y': None,
'X': None,
}
print dict1
# {'Q': 1, 'P': 0, 'S': None, 'R': 0, 'T': '', 'W': [], 'V': {}, 'Y': None, 'X': None}
print dict_without_empty_values(dict1)
# {'Q': 1}