Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a deeply nested dictionary using tuples?

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 this:


class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

Testing:

a = AutoVivification()

a[1][2][3] = 4
a[1][3][3] = 5
a[1][2]['test'] = 6

print a

Output:

{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}

I have a case where I want to set a node given some arbitrary tuple of subscripts. If I don't know how many layers deep the tuple will be, how can I design a way to set the appropriate node?

I'm thinking that perhaps I could use syntax like the following:

mytuple = (1,2,3)
a[mytuple] = 4

But I'm having trouble coming up with a working implementation.


Update

I have a fully working example based on @JCash's answer:

class NestedDict(dict):
    """                                                                       
    Nested dictionary of arbitrary depth with autovivification.               

    Allows data access via extended slice notation.                           
    """
    def __getitem__(self, keys):
        # Let's assume *keys* is a list or tuple.                             
        if not isinstance(keys, basestring):
            try:
                node = self
                for key in keys:
                    node = dict.__getitem__(node, key)
                return node
            except TypeError:
            # *keys* is not a list or tuple.                              
                pass
        try:
            return dict.__getitem__(self, keys)
        except KeyError:
            raise KeyError(keys)
    def __setitem__(self, keys, value):
        # Let's assume *keys* is a list or tuple.                             
        if not isinstance(keys, basestring):
            try:
                node = self
                for key in keys[:-1]:
                    try:
                        node = dict.__getitem__(node, key)
                    except KeyError:
                        node[key] = type(self)()
                        node = node[key]
                return dict.__setitem__(node, keys[-1], value)
            except TypeError:
                # *keys* is not a list or tuple.                              
                pass
        dict.__setitem__(self, keys, value)

Which can achieve the same output as above using extended slice notation:

d = NestedDict()
d[1,2,3] = 4
d[1,3,3] = 5
d[1,2,'test'] = 6
like image 765
Jeff Klukas Avatar asked Feb 25 '13 22:02

Jeff Klukas


1 Answers

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)
like image 110
JCash Avatar answered Sep 23 '22 21:09

JCash