Python: An elegant way to delete empty lists from Python dictionary

前端 未结 6 648
庸人自扰
庸人自扰 2021-01-11 19:30

I have a dictionary as:

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

I wish to eliminate the empty values as:

6条回答
  •  终归单人心
    2021-01-11 19:37

    To fix your function, change del[k] to del 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:

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

    This assumes you want to eliminate both empty list and None values, and actually removes any item with a "false" value.

提交回复
热议问题