I have a dictionary as:
default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []}
I wish to eliminate the empty values as:
default = {'a': ['alpha'], 'b': ['beta','gamma']}
I wrote a function (following an example found on the web)
def remove_empty_keys(d):
for k in d.keys():
try:
if len(d[k]) < 1:
del[k]
except:
pass
return(d)
I have the following questions:
1- I didn’t find the mistake why it always returns following –
remove_empty_keys(default)
{'a': ['alpha'], 'b': ['beta'], 'g': []}
2- Is there a built-in function to eliminate/delete Null/None/empty values from Python dictionary without creating a copy of the original dictionary?
To fix your function, change
del[k]todel d[k]. There is no function to delete values in place from a dictionary.What you are doing is deleting the variable
k, not changing the dictionary at all. This is why the original dictionary is always returned.Rewritten, your function might look like:
This assumes you want to eliminate both empty list and
Nonevalues, and actually removes any item with a “false” value.