Storing class objects dynamically in an array

Dave Angel d at davea.name
Mon Jan 21 21:30:57 EST 2013


On 01/21/2013 08:56 PM, Brian D wrote:
> Hi,
>
> I'm trying to instantiate a class object repeated times, dynamically for as many times as are required, storing each class object in a container to later write out to a database. It kind of looks like what's needed is a two-dimensional class object, but I can't quite conceptualize how to do that.
>
> A simpler approach might be to just store class objects in a dictionary, using a reference value (or table row number/ID) as the key.
>
> In the real-world application, I'm parsing row, column values out of a table in a document which will have not more than about 20 rows, but I can't expect the document output to leave columns well-ordered. I want to be able to call the class objects by their respective row number.
>
> A starter example follows, but it's clear that only the last instance of the class is stored.
>
> I'm not quite finding what I want from online searches, so what recommendations might Python users make for the best way to do this?
>
> Maybe I need to re-think the approach?
>
>
> Thanks,
> Brian
>
>
>
> class Car(object):
>
>      def __init__(self, Brand, Color, Condition):
>          self.Brand = Brand
>          self.Color = Color
>          self.Condition = Condition
>
> brandList = ['Ford', 'Toyota', 'Fiat']
> colorList = ['Red', 'Green', 'Yellow']
> conditionList = ['Excellent', 'Good', 'Needs Help']
>
> usedCarLot = {}
>
> for c in range(0, len(brandList)):
>      print c, brandList[c]
>      usedCarLot[c] = Car
>      usedCarLot[c].Brand = brandList[c]
>      usedCarLot[c].Color = colorList[c]
>      usedCarLot[c].Condition = conditionList[c]

Or even better:  (untested)

   for c, vals in enumerate(zip(brandList, colorList, conditionList)):
        usedCarLot[c] = Car(*vals)
>
> for k, v in usedCarLot.items():
>      print k, v.Brand, v.Color, v.Condition
>
>
>>>>
> 0 Ford
> 1 Toyota
> 2 Fiat
> 0 Fiat Yellow Needs Help
> 1 Fiat Yellow Needs Help
> 2 Fiat Yellow Needs Help
>


-- 
DaveA



More information about the Python-list mailing list