Efficient way to remove keys with empty strings from a dict

前端 未结 17 1274

I have a dict and would like to remove all the keys for which there are empty value strings.

metadata = {u\'Composite:PreviewImage\': u\'(Binary data 101973          


        
17条回答
  •  盖世英雄少女心
    2020-11-27 13:40

    If you really need to modify the original dictionary:

    empty_keys = [k for k,v in metadata.iteritems() if not v]
    for k in empty_keys:
        del metadata[k]
    

    Note that we have to make a list of the empty keys because we can't modify a dictionary while iterating through it (as you may have noticed). This is less expensive (memory-wise) than creating a brand-new dictionary, though, unless there are a lot of entries with empty values.

提交回复
热议问题