检查字典中的值是否被定义/具有零长度的最恶意的方式 [英] The most Pythonic way of checking if a value in a dictionary is defined/has zero length

查看:159
本文介绍了检查字典中的值是否被定义/具有零长度的最恶意的方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个字典,我想检查一个键是否映射到一个非空值。一种方法是使用len函数:

Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if len(mydict["key"]) > 0 else "False"  # prints true
print "True" if len(mydict["emptykey"]) > 0 else "False"  # prints false

但是,可以依赖Python的语义,一个对象被定义为它的计算结果为真,并忽略len调用:

However, one can rely on the semantics of Python and how if an object is defined it evaluates to true and leave out the len call:

mydict = {"key" : "value", "emptykey" : ""}
print "True" if mydict["key"] else "False"  # prints true
print "True" if mydict["emptykey"] else "False"  # prints false

但是,我不确定哪个更加Pythonic。第一个感觉是显式比隐式更好,但第二个感觉简单比复杂更好。

However, I'm not sure which is more Pythonic. The first feels "explicit is better than implicit", however the second feels "simple is better than complex".

我也想知道省略len调用是否可以咬我作为我正在使用的dict不一定包含字符串,但可以包含其他lenable类型(列表,集等)。 OTOH,在前者(用len调用)如果None被存储为一个值,代码将炸毁,而非len版本将正常工作(将eval为false)。

I also wonder if the leaving out the len call could bite me as the dict I'm working with doesn't necessarily contain strings, but could contain other len-able types (lists, sets, etc). OTOH, in the former (with the len call) if None gets stored as a value the code will blow up, whereas the non-len version will work as expected (will eval to false).

哪个版本更安全,更多Pythonic?

Which version is safer and more Pythonic?

编辑:澄清假设:我知道键是在字典中,我知道价值观将会放出。我也不能避免零长度值输入字典。

clarifying assumptions: I know the key is in the dictionary, and I know values will be len-able. I also cannot avoid having zero-length values enter the dictionary.

编辑#2:似乎人们缺少我的问题的要点。我不想确定最奇怪的/最安全的方式检查一个键是否存在于字典,我试图检查 一个值是否为零长度

Edit #2: It seems like people are missing the point of my question. I'm not trying to determine the most Pythonic/safest way of checking if a key is present in a dictionary, I'm trying to check if a value has zero length or not

推荐答案

如果您知道键在字典中,请使用

If you know the key is in the dictionary, use

if mydict["key"]:
    ...


b $ b

这很简单,容易阅读,并且说如果绑定到'key'的值计算 True ,做一些事情。要知道的重要信息是容器类型(dict,list,tuple,str等)只评估 True 如果他们的 len 大于0。

It is simple, easy to read, and says, "if the value tied to 'key' evaluates to True, do something". The important tidbit to know is that container types (dict, list, tuple, str, etc) only evaluate to True if their len is greater than 0.

如果你的前提是一个键在前面,它还会产生一个 KeyError 违反了

It will also raise a KeyError if your premise that a key is in mydict is violated.

所有这一切都变成了Pythonic。

All this makes it Pythonic.

这篇关于检查字典中的值是否被定义/具有零长度的最恶意的方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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