Python will throw a KeyError
if the key doesn't exist in the dictionary so you can't write your code in quite the same way as your JavaScript.
(如果字典中不存在键,Python会抛出KeyError
,因此您无法以与JavaScript完全相同的方式编写代码。)
However, if you are operating specifically with dicts as in your example, there is a very nice function mydict.get('key', default)
which attempts to get the key from the dictionary and returns the default value if the key doesn't exist. (但是,如果您像示例中那样专门使用dict进行操作,则有一个非常不错的函数mydict.get('key', default)
,该函数尝试从字典中获取键,如果没有,则返回默认值存在。)
If you just want to default to be None
you don't need to explicitly pass the second argument.
(如果您只想默认为None
,则无需显式传递第二个参数。)
Depending on what your dict contains and how often you expect to access unset keys, you may also be interested in using the defaultdict
from the collections
package.
(根据dict包含的内容以及期望访问未设置键的频率,您可能还对使用collections
包中的defaultdict
感兴趣。)
This takes a factory and uses it to return new values from the __missing__
magic method whenever you access a key that hasn't otherwise been explicitly set. (这需要一个工厂,并在每次访问未显式设置的键时使用它从__missing__
魔术方法返回新值。)
It's particularly useful if your dict is expected to contain only one type. (如果预计您的字典仅包含一种类型,则此功能特别有用。)
from collections import defaultdict
foo = defaultdict(list)
bar = foo["unset"]
# bar is now a new empty list
NB the docs (for 2.7.13) claim that if you don't pass an argument to defaultdict
it'll return None
for unset keys.
(注意,文档(针对2.7.13)声称,如果不将参数传递给defaultdict
它将为None
设置的键返回None
。)
When I tried it (on 2.7.10, it's just what I happened to have installed), that didn't work and I received a KeyError
. (当我尝试它(在2.7.10上,它恰好是我刚安装的)时,它不起作用,我收到了KeyError
。)
YMMV. (YMMV。)
Alternatively, you can just use a lambda: defaultdict(lambda: None)
(另外,您也可以使用lambda: defaultdict(lambda: None)
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…