Efficient way to remove keys with empty strings from a dict

前端 未结 17 1209

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:22

    Building on the answers from patriciasz and nneonneo, and accounting for the possibility that you might want to delete keys that have only certain falsy things (e.g. '') but not others (e.g. 0), or perhaps you even want to include some truthy things (e.g. 'SPAM'), then you could make a highly specific hitlist:

    unwanted = ['', u'', None, False, [], 'SPAM']
    

    Unfortunately, this doesn't quite work, because for example 0 in unwanted evaluates to True. We need to discriminate between 0 and other falsy things, so we have to use is:

    any([0 is i for i in unwanted])
    

    ...evaluates to False.

    Now use it to del the unwanted things:

    unwanted_keys = [k for k, v in metadata.items() if any([v is i for i in unwanted])]
    for k in unwanted_keys: del metadata[k]
    

    If you want a new dictionary, instead of modifying metadata in place:

    newdict = {k: v for k, v in metadata.items() if not any([v is i for i in unwanted])}
    

提交回复
热议问题