0

I'm working out a class to allow nested dictionaries to be indexed like ND arrays, so I want to be able to put a colon in one of the key "slots" so I can get all of the matching entries from that level of the nest, but I can't find anything on how to handle colon operators being passed through __getitem__ that seem to address this. Maybe there is a better way to do this, generally that avoids this need. Here is my class so far:

class nestedDict(dict):
    def __init__(self, dictionary):
        super().__init__(dictionary)
        self.dictionary = dictionary
        self.depth = self.getDepth()
    
    def getDepth(self, d=1):
        nest = next(iter(self.values()))
        if type(nest) is dict:
            d+=1
            nest = nestedDict(nest)
            d = nest.getDepth(d=d)
        return d
    
    def __getitem__(self, __key: Any) -> Any:
        # Check to see the first index, and return all the sub dictionaries if it's a colon
        # If it's not a colon, return the keyed dictionary (just like normal) 
        return super().__getitem__(__key)

I'd like to be able to take a dict like this

d = {'x': 
          {'i':{'A':1,'B':2,'C':3}, 'ii':{'A':4, 'B':5, 'C':6}, 'iii':{'A':7}}, 
     'y': 
          {'i':{'A':8,'B':9,'C':10},'ii':{'A':11,'B':12,'C':13},'iii':{'A':14}}}

and index into it using keys or the colon for any level of the nesting. For example...

d['x'][:]['A'] = (1, 4, 7)
d[:]['i']['A'] = (1, 8)

0 Answers0