【问题标题】:More nest Python nested dictionaries更多嵌套 Python 嵌套字典
【发布时间】:2010-03-24 17:48:11
【问题描述】:

看完What is the best way to implement nested dictionaries?为什么做错了:

c = collections.defaultdict(collections.defaultdict(int))

在python中?我认为这会产生

{key:{key:1}}

还是我想错了?

【问题讨论】:

    标签: python collections nested


    【解决方案1】:

    defaultdict 的构造函数需要一个可调用对象。 defaultdict(int) 是默认字典对象,而不是可调用对象。但是,使用lambda 可以工作:

    c = collections.defaultdict(lambda: collections.defaultdict(int))
    

    这是可行的,因为我传递给外部 defaultdict 的是一个可调用对象,它在调用时会创建一个新的 defaultdict

    这是一个例子:

    >>> import collections
    >>> c = collections.defaultdict(lambda: collections.defaultdict(int))
    >>> c[5][6] += 1
    >>> c[5][6]
    1
    >>> c[0][0]
    0
    >>> 
    

    【讨论】:

      【解决方案2】:

      Eli Bendersky 为这个问题提供了一个很好的直接答案。将数据重组为

      可能会更好
      >>> import collections
      >>> c = collections.defaultdict(int)
      >>> c[1, 2] = 'foo'
      >>> c[5, 6] = 'bar'
      >>> c
      defaultdict(<type 'int'>, {(1, 2): 'foo', (5, 6): 'bar'})
      

      取决于你的实际需要。

      【讨论】:

      • 这是一个质量观察。
      猜你喜欢
      • 2022-01-25
      • 2018-01-29
      • 2019-12-04
      • 2018-05-31
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      相关资源
      最近更新 更多