Efficient way to remove keys with empty strings from a dict

前端 未结 17 1135

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

    If you really need to modify the original dictionary:

    empty_keys = [k for k,v in metadata.iteritems() if not v]
    for k in empty_keys:
        del metadata[k]
    

    Note that we have to make a list of the empty keys because we can't modify a dictionary while iterating through it (as you may have noticed). This is less expensive (memory-wise) than creating a brand-new dictionary, though, unless there are a lot of entries with empty values.

    0 讨论(0)
  • 2020-11-27 13:40

    For python 3

    dict((k, v) for k, v in metadata.items() if v)
    
    0 讨论(0)
  • 2020-11-27 13:41

    If you want a full-featured, yet succinct approach to handling real-world data structures which are often nested, and can even contain cycles, I recommend looking at the remap utility from the boltons utility package.

    After pip install boltons or copying iterutils.py into your project, just do:

    from boltons.iterutils import remap
    
    drop_falsey = lambda path, key, value: bool(value)
    clean = remap(metadata, visit=drop_falsey)
    

    This page has many more examples, including ones working with much larger objects from Github's API.

    It's pure-Python, so it works everywhere, and is fully tested in Python 2.7 and 3.3+. Best of all, I wrote it for exactly cases like this, so if you find a case it doesn't handle, you can bug me to fix it right here.

    0 讨论(0)
  • 2020-11-27 13:42

    BrenBarn's solution is ideal (and pythonic, I might add). Here is another (fp) solution, however:

    from operator import itemgetter
    dict(filter(itemgetter(1), metadata.items()))
    
    0 讨论(0)
  • 2020-11-27 13:42

    Some of Methods mentioned above ignores if there are any integers and float with values 0 & 0.0

    If someone wants to avoid the above can use below code(removes empty strings and None values from nested dictionary and nested list):

    def remove_empty_from_dict(d):
        if type(d) is dict:
            _temp = {}
            for k,v in d.items():
                if v == None or v == "":
                    pass
                elif type(v) is int or type(v) is float:
                    _temp[k] = remove_empty_from_dict(v)
                elif (v or remove_empty_from_dict(v)):
                    _temp[k] = remove_empty_from_dict(v)
            return _temp
        elif type(d) is list:
            return [remove_empty_from_dict(v) for v in d if( (str(v).strip() or str(remove_empty_from_dict(v)).strip()) and (v != None or remove_empty_from_dict(v) != None))]
        else:
            return d
    
    0 讨论(0)
提交回复
热议问题