从字典中删除带有空字符串的键的有效方法 [英] Efficient way to remove keys with empty strings from a dict

查看:20
本文介绍了从字典中删除带有空字符串的键的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典,想删除所有有空值字符串的键.

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''}

最好的方法是什么?

推荐答案

Python 2.X

dict((k, v) for k, v in metadata.iteritems() if v)

<小时>

Python 2.7 - 3.X


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.

这篇关于从字典中删除带有空字符串的键的有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆