Edward Edward - 1 year ago 88
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:


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 Source

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
        return 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download