我有以下问题:
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)
正如您在评论中看到的那样,似乎不可能编写以下版本give_it_to_me
:
- 永远不会崩溃
defaultdict
触发s的默认值
还是我错了?