views:

79

answers:

4

I am creating a data structure dynamically that holds car information. The dictionary looks something like this:

cars = {'toyota': {'prius': {'transmission':'automatic', 'mpg':30, 'misc':[]}}}

The outermost dictionary contains car brand (toyota, bmw, etc.), the second dictionary contains model (prius, m5, etc.) and the inner dictionary contains details of the car. Is this the best way to hold this information?

I am both building the data structure and accessing it. I can't really think of another way to do it but the code looks kind of messy with a bunch of:

cars['toyota'].setdefault('prius', {}).setdefault('misc', []).append('hello')
A: 

Why not create JSON structure? Semantically you might be able to gain a little more expressiveness rather than accessing your data as dictionary elements.

Gangadhar
I believe JSON would still not be what Lance actually wants.
AJ
+5  A: 

Python has classes. I don't know if it makes sense with your data structure, but you could organize everything into a collection of Car classes.

Justin Ardini
+11  A: 

As Justin suggested, classes would be ideal.

You could easily do something like this:

class Car(object):
    def __init__(self, make, model=None, trans=None, mpg=None, misc=None):
        if make == 'Toyta' and model is None:
            model = 'Prius'
        self.make = make
        self.model = model
        self.transmission = trans
        self.mpg = mpg
        if misc is None:
            self.misc = []
    #other class stuff here
    def __str__(self):
        return "Make: {make} Model: {model} Mpg: {mpg}".format(make=self.make,
                                                               model=self.model,
                                                               mpg=self.mpg)
    def __repr__(self):
        return str(self)

cars = [Car('Toyota', 'Prius', 'Automatic', '30'), 
        Car('Mitsubishi', 'Echo LRX', 'Automatic', '20')]

for car in cars:
    print car

HTH!

Wayne Werner
Nice! I wanted to up vote this but one day after I had reached the limit to upvote, they are still asking me to come back after 3 effing hours. There is some glitch.
AJ
And the nice thing about Python (and similar languages) is that Lance's request of having the data structure be dynamic still works with classes, since you can dynamically add and remove attributes.
JAB
A: 

One idea - flatten the nested dictionary keyed by a multi-segment name separated by period. E.g.

cars.setvalue('toyota.prius.transmission', 'automatic')
cars.setvalue('toyota.prius.mpg', '30')
cars.setvalue('toyota.prius.misc', [])

cars.getvalue('toyota.prius.misc').append('hello')

class Car:
    def setvalue(self, key, value):
        # parse the key and do your mess here, like
        # cars['toyota'].setdefault('prius', {}).setdefault('misc', [])
Wai Yip Tung