Efficient way to remove keys with empty strings from a dict

前端 未结 17 1273

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

    Based on Ryan's solution, if you also have lists and nested dictionaries:

    For Python 2:

    def remove_empty_from_dict(d):
        if type(d) is dict:
            return dict((k, remove_empty_from_dict(v)) for k, v in d.iteritems() if v and remove_empty_from_dict(v))
        elif type(d) is list:
            return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
        else:
            return d
    

    For Python 3:

    def remove_empty_from_dict(d):
        if type(d) is dict:
            return dict((k, remove_empty_from_dict(v)) for k, v in d.items() if v and remove_empty_from_dict(v))
        elif type(d) is list:
            return [remove_empty_from_dict(v) for v in d if v and remove_empty_from_dict(v)]
        else:
            return d
    

提交回复
热议问题