簡體   English   中英

如何在 Python 中使用不同類型的對象構建嵌套的 defaultdicts

[英]how do you build nested defaultdicts in Python with objects of a different type

我正在嘗試重寫以下代碼

dct = {}
x = 'x'
y = 'y'
z = 'z'
if x not in dct:
    dct[x] = defaultdict(dict)
if y not in dct[x]:
    dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
    dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))
dct[x][y][z]['b'][0]['g']+=1

沒有以下幾行:

if x not in dct:
    dct[x] = defaultdict(dict)
if y not in dct[x]:
    dct[x][y] = defaultdict(dict)
if z not in dct[x][y]:
    dct[x][y][z] = defaultdict(list)
dct[x][y][z]['b'].append(defaultdict(int))

理想情況下,我希望有語法,例如

dct = 'state what it is'
dct[x][y][z]['b'][0]['g']+=1

我編寫了一個自定義的defaultdict實現,它可以做到任意深度,這與之前答案中的固定深度不同。

class DefaultDict(dict):
    def __missing__(self, name):
        rval=type(self)()
        self.__setitem__(name, rval)
        return rval

這是一些示例用法:

>>> dct=DefaultDict()
>>> dct[0][1]['bees'][('any','hashable','object')]=2
>>> dct[0][1]['bees'][('any','hashable','object')]
2
>>> 0 in dct
True
>>> 1 in dct
False
>>> dct
{0: {1: {'bees': {('any', 'hashable', 'object'): 2}}}}

使用 lambda。

from collections import defaultdict as dd

dct = dd(lambda: dd(lambda: dd(int)))

dct["foo"][1][("a", 7)] += 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM