簡體   English   中英

編寫dict和defaultdict的代碼

[英]Writing code for dict and defaultdict

我有以下問題:

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的默認值

還是我錯了?

您可能需要在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

使用try .. except

try
    return d['it']
except KeyError:
    return None

為什么defaultdict.get無法按預期工作

defaultdict使用__missing__方法實現。 當密鑰k不在字典中時, dict.__getitem__(k) __missing__方法僅由dict[k] (或dict.__getitem__(k)dict.__getitem__(k)

defaultdict.__missing__文檔還提到:

請注意,除__getitem__()之外的任何操作都不會調用__missing__() __getitem__() 這意味着get()將像普通字典一樣,返回None作為默認值,而不是使用default_factory

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM