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

前端 未结 6 635
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2021-01-11 19:51

    There's no builtin for this (AFAIK), but you can do it easily with a dict comprehension:

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

    If you're stuck with an older version of python (pre 2.7 without dict comprehensions), you can use the dict constructor:

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

    Note that this doesn't operate in place (as per your second question). And dictionaries don't support slice assignment like lists do, so the best* you can really do to get this all done in place is:

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

    *of course the term "best" is completely subjective.

提交回复
热议问题