Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中使用默认值定义多维字典?_Python_Dictionary_Autovivification - Fatal编程技术网

如何在python中使用默认值定义多维字典?

如何在python中使用默认值定义多维字典?,python,dictionary,autovivification,Python,Dictionary,Autovivification,我想修改下一个dict定义: class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value 为了能够以下一种方式使用它: totals[year][month] += amount 与…一起使用 与…一起使用 最后,我使用了带元组的计数器作为键。最后,我使用了带元组的计数器作为键。你看过集合了吗。de

我想修改下一个dict定义:

class Vividict(dict):
      def __missing__(self, key):
           value = self[key] = type(self)()
           return value
为了能够以下一种方式使用它:

totals[year][month] += amount    
与…一起使用

与…一起使用


最后,我使用了带元组的计数器作为键。

最后,我使用了带元组的计数器作为键。

你看过集合了吗。defaultdict?你看过集合了吗。defaultdict?d[年][月][日]+=1@buslik这是行不通的,因为如果你用任何结构
d['year']['month']+=1
,您将
d['year']['month']
的值设置为
int
对象。通过d=defaultdict(计数器),我们正在创建二维dict。一个维度来自defaultdict,另一个维度来自计数器。@buslik您完全正确。但是,正如我已经说过的,你不可能做到这一点。您应该在
dict
int
.d[年][月][日]+=1@buslik这是行不通的,因为如果您使用任何结构
d['year']['month']+=1
,您可以将
d['year']['month']
的值设置为
int
对象我们正在创建二维dict。一个维度来自defaultdict,另一个维度来自Counter。@buslik您完全正确。但是,正如我已经说过的,你不可能做到这一点。您应该在
dict
int
之间进行选择。
from collections import defaultdict, Counter

d = defaultdict(Counter)
d['year']['month'] += 1