#This program works with a dictionary of stock information import csv def cmp (value, basis): if value > basis: return 1 elif value < basis: return -1 else: return 0 #write stocks as comma-separated values (csv) with open('stocks.csv', 'w') as csvfile: #Establish the names of the fields fieldnames = ['symbol', 'firm_name', 'price', 'change', 'pct'] #Establish writer as a csv Dict.writer object that has these field names #Note: this does NOT put a header in the csv file writer = csv.DictWriter(csvfile, fieldnames=fieldnames) #Write the data to the csv file. If you open this file in Excel, it will look like a spreadsheet. #If you open it in a text editor, it will look like text separated by commas writer.writerow({'symbol': 'GOOG', 'firm_name': 'Google Inc.', 'price': 505.24, 'change': 0.47, 'pct': 0.09}) writer.writerow({'symbol': 'YHOO', 'firm_name': 'Yahoo! Inc.', 'price': 27.38, 'change': 0.33, 'pct': 1.22}) writer.writerow({'symbol': 'CNET', 'firm_name': 'CNET Networks, Inc.', 'price': 8.62, 'change': -0.13, 'pct': -1.49}) #read the stock data into an object named stocks, print status messages stocks = csv.reader(open('stocks.csv')) #Set up labels to make output more friendly. cmp is -1 if xy status_labels = {-1: 'down', 0: 'unchanged', 1: 'up'} dictlist = [] for line in stocks: dictlist.append(dict(zip(['symbol','firm_name','price','change','pct'],line))) for d in dictlist: test = float(d['change']) status = status_labels[cmp(test, 0.0)] print ('%s is %s %s%%' % (d['firm_name'], status, d['pct']))