Question
Asked By – ensnare
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 bytes)',
u'EXIF:CFAPattern2': u''}
What is the best way to do this?
Now we will see solution for issue: Efficient way to remove keys with empty strings from a dict
Answer
Python 2.X
dict((k, v) for k, v in metadata.iteritems() if v)
Python 2.7 – 3.X
{k: v for k, v in metadata.items() if v}
Note that all of your keys have values. It’s just that some of those values are the empty string. There’s no such thing as a key in a dict without a value; if it didn’t have a value, it wouldn’t be in the dict.
This question is answered By – BrenBarn
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0