Thijs Thijs - 4 months ago 7
Python Question

Dict Class empty result

My datasource provides dicts, I would like to enricht the dicts and use them for something else.
But I can't get my head around the class to make a new dict, whatever I do, it always returns an empty dict.

class car(dict):
def __init__(self, carId, data):
self.carId = carId
self.brand = data['Brand']
self.type = data['Type']

def addColor(self, color):
self.color = color

car1 = {'Brand': 'Volkswagen', 'Type': 'Polo'}
car2 = {'Brand': 'Volvo', 'Type': 'C30'}

car1b = car("someID", car1)

print car1b['someID']

Answer

You need to change the self.carId = carId to self[carId] = carId .

Try this

class car(dict):
    def __init__(self, carId, data):
        self[carId] = carId
        self.brand = data['Brand']
        self.type = data['Type']

    def addColor(self, color):
        self.color = color

car1 = {'Brand': 'Volkswagen', 'Type': 'Polo'}
car2 = {'Brand': 'Volvo', 'Type': 'C30'}

car1b = car("someID", car1)

print( car1b["someID"])
Comments