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

前端 未结 6 680
庸人自扰
庸人自扰 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:49

    Michael's answer is correct.

    Stepping back, you might be able to avoid creating those empty lists at all, by use of collections.defaultdict(list)

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

提交回复
热议问题