Edward Edward - 10 days ago 5
Python Question

Reading in a CSV file AND sorting it in Python

I am trying to read in a CSV file that looks like this:

ruby,2,100
diamond,1,400
emerald,3,250
amethyst,2,50
opal,1,300
sapphire,2,500
malachite,1,60


Here is some code I have been experimenting with.

class jewel:
def __init__(gem, name, carat, value):
gem.name = name
gem.carot = carat
gem.value = value
def __repr__(gem):
return repr((gem.name, gem.carat, gem.value))

jewel_objects = [jewel('diamond', '1', 400),
jewel('ruby', '2', 200),
jewel('opal', '1', 600),
]

aList = [sorted(jewel_objects, key=lambda jewel: (jewel.value))]
print aList


I would like to read in the values and assign them to name, carat, and value but I'm not sure how to do so. Then once I get them read in I would like to sort them by value per carat so value/carat. I have done quite a bit of searching and have came up blank. Thank you very much for your help in advance.

Answer

You need to do two things here, the first is actually loading the data into the objects. I recommend you look at the 'csv' module in the standard python library for this. It's very complete and will read each row and make it easily accessable

CSV docs: http://docs.python.org/library/csv.html

I would create a list of the objects, and then implement either an cmp function in your object, or (if you're using an older version of python) you can pass a function to sorted() that would define it. You can get more info about sorting in the python wiki

Wiki docs: http://wiki.python.org/moin/HowTo/Sorting

You would implement the cmp function like this in your class (this can be made a bit more efficent, but I'm being descriptive here)

def __cmp__(gem, other):
    if (gem.value / gem.carot) < (other.value / other.carot):
        return -1
    elif (gem.value / gem.carot) > (other.value / other.carot): 
        return 1
    else:
        return 0