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

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

    You can use dict comprehension: -

    >>> default = {'a': ['alpha'], 'b': ['beta','gamma'], 'g': []}
    
    >>> {key: value for key, value in default.iteritems() if value}
    {'a': ['alpha'], 'b': ['beta', 'gamma']}
    

提交回复
热议问题