簡體   English   中英

在其中細分字典和嵌套字典

[英]Subclassing dict and nested dicts in it

我有一個嵌套的字典,我想將其轉換為以下子類:

class SubDict(dict):
    def __getattr__(self, attr):
        if attr in self.keys():
            return self.get(attr)

如果我這樣做,則對基本命令非常有用:

my_nested_dict = SubDict(my_nested_dict)

但是我也需要將嵌套的轉換為SubDict。 我該如何實現?

謝謝!

您需要遞歸嵌套字典,然后遞歸轉換它們:

class SubDict(dict):
    def __init__(self, *args, **kw):
        super(SubDict, self).__init__(*args, **kw)
        for key, value in self.iteritems():
            if isinstance(value, dict):
                self[key] = SubDict(value)

您有沒有研究過collections.defaultdict 您可以很容易地從頭開始創建樹:

import defaultdict

def Tree(): return defaultdict(tree)

如果您的SubDict類除了您在此處顯示的內容外沒有執行其他操作,則這是Harold Cooper在Github上作為 defaultdict的工作:

def tree(): return defaultdict(tree)

暫無
暫無

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

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