Efficient way to remove keys with empty strings from a dict

前端 未结 17 1215

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

    Quick Answer (TL;DR)

    Example01

    ### example01 -------------------
    
    mydict  =   { "alpha":0,
                  "bravo":"0",
                  "charlie":"three",
                  "delta":[],
                  "echo":False,
                  "foxy":"False",
                  "golf":"",
                  "hotel":"   ",                        
                }
    newdict =   dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(vdata) ])
    print newdict
    
    ### result01 -------------------
    result01 ='''
    {'foxy': 'False', 'charlie': 'three', 'bravo': '0'}
    '''
    

    Detailed Answer

    Problem

    • Context: Python 2.x
    • Scenario: Developer wishes modify a dictionary to exclude blank values
      • aka remove empty values from a dictionary
      • aka delete keys with blank values
      • aka filter dictionary for non-blank values over each key-value pair

    Solution

    • example01 use python list-comprehension syntax with simple conditional to remove "empty" values

    Pitfalls

    • example01 only operates on a copy of the original dictionary (does not modify in place)
    • example01 may produce unexpected results depending on what developer means by "empty"
      • Does developer mean to keep values that are falsy?
      • If the values in the dictionary are not gauranteed to be strings, developer may have unexpected data loss.
      • result01 shows that only three key-value pairs were preserved from the original set

    Alternate example

    • example02 helps deal with potential pitfalls
    • The approach is to use a more precise definition of "empty" by changing the conditional.
    • Here we only want to filter out values that evaluate to blank strings.
    • Here we also use .strip() to filter out values that consist of only whitespace.

    Example02

    ### example02 -------------------
    
    mydict  =   { "alpha":0,
                  "bravo":"0",
                  "charlie":"three",
                  "delta":[],
                  "echo":False,
                  "foxy":"False",
                  "golf":"",
                  "hotel":"   ",
                }
    newdict =   dict([(vkey, vdata) for vkey, vdata in mydict.iteritems() if(str(vdata).strip()) ])
    print newdict
    
    ### result02 -------------------
    result02 ='''
    {'alpha': 0,
      'bravo': '0', 
      'charlie': 'three', 
      'delta': [],
      'echo': False,
      'foxy': 'False'
      }
    '''
    

    See also

    • list-comprehension
    • falsy
    • checking for empty string
    • modifying original dictionary in place
    • dictionary comprehensions
    • pitfalls of checking for empty string

提交回复
热议问题