1

我有以下问题:

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

  1. 永远不会崩溃
  2. defaultdict触发s的默认值

还是我错了?

4

2 回答 2

3

give_it_to_me您可能需要在函数中添加更多代码。

使用try except语句检查现有密钥。

例如:

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
于 2013-11-22T14:10:30.917 回答
1

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 that get() will, like normal dictionaries, return None as a default rather than using default_factory.

于 2013-11-22T14:51:19.407 回答