What I'm trying to do

I'm trying to make a class that can store and manipulate multiple sets of data.

However, I'm having trouble making accessing the data as easy and intuitive as possible. The object is intended to essentially just be a nested dictionary, with the layout looking something like:

data = { "File1_Column1": {'header': [...],
                           'data':   [...]},
         "File1_Column2": {'header': [...],
                           'data':   [...]}, ...}

What I want to happen

Assuming I have an instance of this class named data, I want data['File1_Column1']['header'] and data['File1_Column1']['data'] to return what one would expect, but I'd also like data['File1_Column1'] to return the same thing as data['File1_Column1']['data']. I want this because I can foresee myself using the data list 99% of the time, and this would make it more convenient.

The former two are pretty straightforward to do by simply utilizing __getitem__, however, I'm really struggling to get the latter to work.

The closest I've gotten is shown in my simplified code below. I've tried implementing an if-statement to the Data class's __getitem__ method in various ways, checking whether or not the Subscript class's __getitem__ method was called, but have had no luck.

What I've tried already

class Data:

    def __init__(self):
        self._data = {}

    def append(self, label, data):
        self._data[label] = data

    def __getitem__(self, label):

        class Subscript:

            def __init__(self, data):
                self._data = data

            def __getitem__(self, label):
                return self._data[label]

        subdata = Subscript(self._data[label])
        return subdata

data = Data()
example = {'header': ['Trace', 'Unit'], 'data': [1, 2, 3, 4]}
data.append('Label', example)

The results

<__main__.Data.__getitem__.<locals>.Subscript object at 0x007B4B10>
[1, 2, 3, 4]
['Trace', 'Unit']

What I expect to happen

[1, 2, 3, 4]
[1, 2, 3, 4]
['Trace', 'Unit']

Is there a way to do this?

0 Answers