![](/img/trans.png)
[英]How to create a dictionary from existing list? Key Value must be the amount of repeats for that key
[英]How to automatically create value from non existing key with a function
背景:
假設我有一個函數(當然在實際中這將是一個更復雜的函數):
def f(x):
return str(x)
如果我想存儲值以避免不必要的重新計算,我可以創建一個像這樣的dict
:
my_dict = {x: f(x) for x in range(5)}
不過,如果我不事先知道哪些值我可能需要,例如10
, my_dict[10]
顯然產生一個KeyError
。
解決這個問題的一種方法是:
my_dict = {}
def get_value(x):
if x not in my_dict:
my_dict[x] = f(x)
return my_dict[x]
get_value(10)
問題:這看起來與defaultdict
非常相似:有沒有辦法使直觀(但破壞) my_dict = defaultdict(f)
工作,即當一個鍵x
不存在時,它應該調用f(x)
而不是f()
創建默認值?
您可以構建自己的dict
數據類型。 在你的情況下, __missing__
將有所幫助。 如果沒有密鑰, __missing__
方法會觸發您的自定義工作。 下面是一個簡單的例子。
from collections import UserDict
class MyDict(UserDict):
def __missing__(self, key):
self[key] = 2*key
return self[key]
if __name__ == '__main__': # test
a = MyDict((x, 2*x) for x in range(5))
print(a)
# {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
a[5]
# 10
print(a)
# {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5:10}
另請注意, UserDict
是字典對象的包裝器,使您可以輕松地對字典數據類型進行子類化。
查看官方文檔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.