### 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'}
'''
- 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 -------------------
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 ='''
{'charlie': 'three', 'echo': False,
'foxy': 'False', 'delta': [],
'bravo': '0', 'alpha': 0
}
'''