Efficient way to remove keys with empty strings from a dict

前端 未结 17 1218

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

    I read all replies in this thread and some referred also to this thread: Remove empty dicts in nested dictionary with recursive function

    I originally used solution here and it worked great:

    Attempt 1: Too Hot (not performant or future-proof):

    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
    

    But some performance and compatibility concerns were raised in Python 2.7 world:

    1. use isinstance instead of type
    2. unroll the list comp into for loop for efficiency
    3. use python3 safe items instead of iteritems

    Attempt 2: Too Cold (Lacks Memoization):

    def scrub_dict(d):
        new_dict = {}
        for k, v in d.items():
            if isinstance(v,dict):
                v = scrub_dict(v)
            if not v in (u'', None, {}):
                new_dict[k] = v
        return new_dict
    

    DOH! This is not recursive and not at all memoizant.

    Attempt 3: Just Right (so far):

    def scrub_dict(d):
        new_dict = {}
        for k, v in d.items():
            if isinstance(v,dict):
                v = scrub_dict(v)
            if not v in (u'', None, {}):
                new_dict[k] = v
        return new_dict
    

提交回复
热议问题