私は次のdictの定義を変更したいと思います:Pythonでデフォルト値を持つ多次元辞書を定義する方法は?
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
は、次の方法でそれを使用できるようにするには:
totals[year][month] += amount
私は次のdictの定義を変更したいと思います:Pythonでデフォルト値を持つ多次元辞書を定義する方法は?
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
は、次の方法でそれを使用できるようにするには:
totals[year][month] += amount
使用collections.defaultdict
collections.Counter
で。
from collections import defaultdict, Counter
d = defaultdict(Counter)
d['year']['month'] += 1
最後に、タプル付きのカウンターをキーとして使用しました。
あなたはcollections.defaultdictを見ましたか? –