【问题标题】:How to define multidimensional dictionary with default value in python?如何在python中定义具有默认值的多维字典?
【发布时间】:2016-10-13 13:57:57
【问题描述】:

我想修改下一个字典定义:

class Vividict(dict):
      def __missing__(self, key):
           value = self[key] = type(self)()
           return value

为了能够在下一个方式中使用它:

totals[year][month] += amount    

【问题讨论】:

  • 你看过 collections.defaultdict 吗?

标签: python dictionary autovivification


【解决方案1】:

collections.defaultdictcollections.Counter 一起使用。

from collections import defaultdict, Counter

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

【讨论】:

  • d[年][月][日] += 1
  • @buslik 无法正常工作,因为如果您使用 d 的任何结构执行 d['year']['month'] += 1,则您将 d['year']['month'] 的值设置为 int 对象。
  • 通过 d = defaultdict(Counter) 我们正在创建二维字典。一个维度来自默认字典,另一个来自 Counter。
  • @buslik 你绝对正确。但是,正如我已经说过的,你无法做到这一点。您应该在dictint 之间进行选择。
【解决方案2】:

最后我使用了带有元组的 Counter 作为键。

【讨论】:

    猜你喜欢
    • 2016-06-25
    • 1970-01-01
    • 2016-01-28
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    相关资源
    最近更新 更多