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:
defaultdict
s Or am I wrong?
You might need a bit more code in your give_it_to_me
function.
Use a try
except
statement to check for an existing key.
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
return d['it']
except KeyError:
return None
Why defaultdict.get
does not work as expected :
defaultdict
is implemented using __missing__ method. __missing__
method is only called by dict[k]
(or dict.__getitem__(k)
) when the key k
is not in a dictionary.
defaultdict.__missing__
documentation also mention that:
Note that
__missing__()
is not called for any operations besides__getitem__()
. This means thatget()
will, like normal dictionaries, return None as a default rather than usingdefault_factory
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.