Efficient way to remove keys with empty strings from a dict

前端 未结 17 1210

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

    "As I also currently write a desktop application for my work with Python, I found in data-entry application when there is lots of entry and which some are not mandatory thus user can left it blank, for validation purpose, it is easy to grab all entries and then discard empty key or value of a dictionary. So my code above a show how we can easy take them out, using dictionary comprehension and keep dictionary value element which is not blank. I use Python 3.8.3

    data = {'':'', '20':'', '50':'', '100':'1.1', '200':'1.2'}
    
    dic = {key:value for key,value in data.items() if value != ''}
    
    print(dic)
    
    {'100': '1.1', '200': '1.2'}
    

提交回复
热议问题