[英]Writing code for dict and defaultdict
I have the following problem: 我有以下问题:
from collections import defaultdict
def give_it_to_me(d):
# This will crash if key 'it' does not exist
return d['it']
def give_it2_to_me(d):
# This will never crash, but does not trigger the default value in defaultdict
return d.get('it2')
d1 = defaultdict(int)
d2 = { 'it' : 55 }
print give_it_to_me(d1)
print give_it_to_me(d2)
print give_it2_to_me(d1)
print give_it2_to_me(d2)
As you can see in the comments, it seems impossible to write a version of give_it_to_me
which: 正如您在评论中看到的那样,编写一个
give_it_to_me
版本似乎是不可能的:
defaultdict
s defaultdict
的默认值 Or am I wrong? 还是我错了?
You might need a bit more code in your give_it_to_me
function. 您可能需要在
give_it_to_me
函数中添加更多代码。
Use a try
except
statement to check for an existing key. 使用
try
except
语句检查现有密钥。
For example: 例如:
def give_it_to_me(d):
# This won't crash if key 'it' does not exist in a normal dict.
# It returns just None in that case.
# It returns the default value of an defaultdict if the key is not found.
try:
return d['it']
except KeyError:
return None
Use try .. except
: 使用
try .. except
:
try
return d['it']
except KeyError:
return None
Why defaultdict.get
does not work as expected : 为什么
defaultdict.get
无法按预期工作 :
defaultdict
is implemented using __missing__ method. defaultdict
使用__missing__方法实现。 __missing__
method is only called by dict[k]
(or dict.__getitem__(k)
) when the key k
is not in a dictionary. 当密钥
k
不在字典中时, dict.__getitem__(k)
__missing__
方法仅由dict[k]
(或dict.__getitem__(k)
) dict.__getitem__(k)
。
defaultdict.__missing__
documentation also mention that: defaultdict.__missing__
文档还提到:
Note that
__missing__()
is not called for any operations besides__getitem__()
.请注意,除
__getitem__()
之外的任何操作都不会调用__missing__()
__getitem__()
。 This means thatget()
will, like normal dictionaries, return None as a default rather than usingdefault_factory
.这意味着
get()
将像普通字典一样,返回None作为默认值,而不是使用default_factory
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.