Michael Markieta
Michael Markieta

Reputation: 442

Using namedtuples to consolidate multiple dictionaries

Given n-number of models which contain m-number of key:value pairs, can namedtuples be used to consolidate that information inside of one object? By consolidate, I mean refactor, so that I can pass around this object and access particular bits of information from it.

How it is organized currently:

Model_1_Dict = {'key1':('value1','value2','value3'),'key2':('value1','value2','value3')}

Model_2_Dict = {'key1':('value1','value2','value3'),'key2':('value1','value2','value3')}

Each model dictionary will have 3 value pairs per key. The key represents an independent variable name (from a regression model), the values represent the beta coefficient, calculated value(x), and an associated function... semantically like this:

>>> Model_1_Dict["Variable Name"]
("Beta Coefficient", "Calculated Value", "myClass.myFunction")

Model_1_Dict["Variable Name"][1] gets updated later on in the code. I could either pass = None at initialization, and then update the value on calculation. Or append the value to the values list object sometime later on (I think this is a non-issue).

I want to know if there is a better way to handle the model information using other structures, such as namedtuples?

Upvotes: 0

Views: 332

Answers (1)

jsbueno
jsbueno

Reputation: 110271

Yes, you could use namedtuples -- up to the point where you said you have to update the information inside the dictionaries. Either tuples and namedtuples are not modifiable. So, if you want to act on your data refering to it by name ratehr than by index number, you should either use a nested dictionary structure - or create a simple class to hold your data.

The advantage of the creating a custom class just for that is that you an restrict the names assigned to it, by having a __slots__ attribute on the class, and you can customize the __repr__ of the object, so that it looks nice on inspection -

Something along:

class Data(object):
    __slots__ = ("beta", "calculated", "function")
    def __init__(self, beta=None, calculated=None, function=None):
        self.beta = beta; self.calculated = calculated; self.function = function

    def __repr__(self):
        return "(%s, %s, %s)"  % (self.beta, self.calculated, self.function)

Which works like this:

>>> Model_1_Dict = {'key1':Data('value1','value2','value3') } 
>>> 
>>> Model_1_Dict
{'key1': (value1, value2, value3)}
>>> Model_1_Dict["key1"].beta = "NewValue"
>>> Model_1_Dict
{'key1': (NewValue, value2, value3)}
>>> 

Upvotes: 1

Related Questions