Efficient way to remove keys with empty strings from a dict

前端 未结 17 1275

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

    Dicts mixed with Arrays

    • The answer at Attempt 3: Just Right (so far) from BlissRage's answer does not properly handle arrays elements. I'm including a patch in case anyone needs it. The method is handles list with the statement block of if isinstance(v, list):, which scrubs the list using the original scrub_dict(d) implementation.
        @staticmethod
        def scrub_dict(d):
            new_dict = {}
            for k, v in d.items():
                if isinstance(v, dict):
                    v = scrub_dict(v)
                if isinstance(v, list):
                    v = scrub_list(v)
                if not v in (u'', None, {}):
                    new_dict[k] = v
            return new_dict
    
        @staticmethod
        def scrub_list(d):
            scrubbed_list = []
            for i in d:
                if isinstance(i, dict):
                    i = scrub_dict(i)
                scrubbed_list.append(i)
            return scrubbed_list
    

提交回复
热议问题