ensnare ensnare - 1 year ago 65
Python Question

Efficient way to remove keys with empty values from a dict

I have a dict and would like to remove all the keys for which there are empty values.

metadata = {u'Composite:PreviewImage': u'(Binary data 101973 bytes)',
u'EXIF:CFAPattern2': u''}

What is the best way to do this?

Answer Source

dict((k, v) for k, v in metadata.iteritems() 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download