简体   繁体   English

编写dict和defaultdict的代码

[英]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版本似乎是不可能的:

  1. Does never crash 永远不会崩溃
  2. Triggers the default value for 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 that get() will, like normal dictionaries, return None as a default rather than using default_factory . 这意味着get()将像普通字典一样,返回None作为默认值,而不是使用default_factory

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM