Python: an elegant way to remove empty lists from a Python dictionary

I have a dictionary like:

default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []}

I want to remove empty values ​​as:

default = {'a': ['alpha'], 'b': ['beta','gamma']}

I wrote a function (following an example found on the Internet)

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 did not find an error, why it always returns the following -

remove_empty_keys(default)
 {'a': ['alpha'], 'b': ['beta'], 'g': []}

2 Is there a built-in function to remove / remove Null / None / empty values ​​from a Python dictionary without creating a copy of the original dictionary?

+7
source share
6 answers

To fix your function, change del[k]to del d[k]. There is no function to remove values ​​from a dictionary.

What you do is delete the variable kwithout changing the dictionary at all. Therefore, the original dictionary is always returned.

, :

def remove_empty_keys(d):
    for k in d.keys():
        if not d[k]:
            del d[k]

, , None , "" .

+8

(AFAIK), dict:

new_dict = {k:v for k,v in original_dict.items() if v}

python (pre 2.7 dict), dict:

new_dict = dict((k,v) for k,v in original_dict.items() if v)

, ( ). slice, , *, , :

new_dict = {k:v for k,v in original_dict.items() if v}
original_dict.clear()
original_dict.update(new_dict)

*, , "" .

+7

dict: -

>>> default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []}

>>> {key: value for key, value in default.iteritems() if value}
{'a': ['alpha'], 'b': ['beta', 'gamma']}
+4
dict((k, v) for k, v in default.iteritems() if v)

, , dict/tuple/list.

+4

.

, , collections.defaultdict(list)

>>> import collections
>>> d = collections.defaultdict(list)
>>> d
defaultdict(<type 'list'>, {})
>>> d["hobbits"].append("Frodo")
>>> d["hobbits"].append("Sam")
>>> d
defaultdict(<type 'list'>, {'hobbits': ['Frodo', 'Sam']})
+1
source

Another option is the following (without creating a new dict):

for e in [k for k,v in default.iteritems() if len(v) == 0]: default.pop(e)
+1
source

All Articles