How can I access a deeply nested dictionary using tuples?

后端 未结 1 848
青春惊慌失措
青春惊慌失措 2021-01-13 09:29

I would like to expand on the autovivification example given in a previous answer from nosklo to allow dictionary access by tuple.

nosklo\'s solution looks like th

相关标签:
1条回答
  • 2021-01-13 09:58

    This seems to work

    def __setitem__(self, key, value):
        if isinstance(key, tuple):
            node = self
            for i in key[:-1]:
                try:
                    node = dict.__getitem__(node, i)
                except KeyError:
                    node = node[i] = type(self)()
            return dict.__setitem__(node, i, value)
        return dict.__setitem__(self, key, value)
    
    0 讨论(0)
提交回复
热议问题