Efficient way to remove keys with empty strings from a dict

前端 未结 17 1277

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

    If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:

    def scrub_dict(d):
        if type(d) is dict:
            return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
        else:
            return d
    

提交回复
热议问题