是否存在用于无限嵌套的defaultdict的标准类

是否存在用于无限嵌套的defaultdict的标准类

本文介绍了是否存在用于无限嵌套的defaultdict的标准类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道Python中是否存在用于无限嵌套字典的标准类吗?

Does anyone know if there's a standard class for an infinitely nestable dictionary in Python?

我发现自己正在重复这种模式:

I'm finding myself repeating this pattern:

d = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
d['abc']['def']['xyz'] += 1

如果要添加另一层"(例如d['abc']['def']['xyz']['wrt']),则必须定义另一个defaultdict嵌套.

If I want to add "another layer" (e.g. d['abc']['def']['xyz']['wrt']), I have to define another nesting of defaultdicts.

为概括这种模式,我编写了一个简单的类,该类重写了__getitem__以自动创建下一个嵌套字典.

To generalize this pattern, I've written a simple class that overrides __getitem__ to automatically create the next nested dictionary.

例如

d = InfiniteDict(('count',0),('total',0))
d['abc']['def']['xyz'].count += 0.24
d['abc']['def']['xyz'].total += 1
d['abc']['def']['xyz']['wrt'].count += 0.143
d['abc']['def']['xyz']['wrt'].total += 1

但是,有人知道这个想法已经存在吗?我已经尝试了谷歌搜索,但是我不确定这叫什么.

However, does anyone know of a pre-existing implementation of this idea? I've tried Googling, but I'm not sure what this would be called.

推荐答案

您可以从defaultdict派生以获得所需的行为:

You can derive from defaultdict to get the behavior you want:

class InfiniteDict(defaultdict):
   def __init__(self):
      defaultdict.__init__(self, self.__class__)

class Counters(InfiniteDict):
   def __init__(self):
      InfiniteDict.__init__(self)
      self.count = 0
      self.total = 0

   def show(self):
      print "%i out of %i" % (self.count, self.total)

此类的用法如下:

>>> d = Counters()
>>> d[1][2][3].total = 5
>>> d[1][2][3].show()
0 out of 5
>>> d[5].show()
0 out of 0

这篇关于是否存在用于无限嵌套的defaultdict的标准类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:25