- Reading in CSV file to add data to a dictionary or tuple
- Open-r CVS
- Open-rwb main
- While (cvs)
- Readline(CVS)
- Readline (main)
- If cvs == main
- Add to record
- Wright (main)
- else
- If cvs > main
- Readline (main)
- else
- If cvs < main
- Readline (cvs)
- AAC,D,20111207,9.83,9.83,9.83,9.83,100
- AACC,D,20111207,3.46,3.47,3.4,3.4,13400
- AACOW,D,20111207,0.3,0.3,0.3,0.3,500
- AAME,D,20111207,1.99,1.99,1.95,1.99,8600
- AAON,D,20111207,21.62,21.9,21.32,21.49,93200
- AAPL,D,20111207,389.93,390.94,386.76,389.09,10892800
- AACC,D,20120127,4.01,4.02,4.03,4.04,40000
- B,D,20120127,4.01,4.02,4.03,4.04,40000
- import csv
- mainReader = csv.DictReader( open("m.csv.txt","rb"), ["id"],"others")
- newReader = csv.DictReader( open("d.csv.txt","rb"), ["id"],"others")
- stocks = {}
- for line in mainReader:
- stocks[line['id']] = line
- print stocks # output hand-formatted
- {
- 'AAC': {'id':'AAC',
- 'others': ['D','20111207','9.83','9.83','9.83','9.83','100']},
- 'AACC': {'id':'AACC',
- 'others': ['D', '20111207', '3.46', '3.47', '3.4', '3.4', '13400']},
- 'AAME': {'id': 'AAME',
- 'others': ['D', '20111207', '1.99', '1.99', '1.95', '1.99', '8600']},
- 'AACOW': {'id': 'AACOW',
- 'others': ['D', '20111207', '0.3', '0.3', '0.3', '0.3', '500']},
- 'AAPL': {'id': 'AAPL', 'others':
- ['D','20111207','389.93','390.94','386.76','389.09','10892800']},
- 'AAON': {'id': 'AAON',
- 'others': ['D', '20111207', '21.62', '21.9', '21.32', '21.49', '93200']}
- }
- for line in newReader:
- # can use if line['id'] in stocks: to check for an existing record if desired
- # in this example, we blindly overwrite any existing entry
- stocks[line['id']] = line
- print stocks # output hand-formatted
- {
- 'AAME': {'id': 'AAME',
- 'others': ['D', '20111207', '1.99', '1.99', '1.95', '1.99', '8600']},
- 'B': {'id': 'B',
- 'others': ['D', '20120127', '4.01', '4.02', '4.03', '4.04', '40000']},
- 'AACC': {'id': 'AACC',
- 'others': ['D', '20120127', '4.01', '4.02', '4.03', '4.04', '40000']},
- 'AAPL': {'id': 'AAPL',
- 'others': ['D','20111207','389.93','390.94','386.76','389.09','10892800']},
- 'AAON': {'id': 'AAON',
- 'others': ['D', '20111207', '21.62', '21.9', '21.32', '21.49', '93200']},
- 'AACOW': {'id': 'AACOW',
- 'others': ['D', '20111207', '0.3', '0.3', '0.3', '0.3', '500']}
- }
- s = stocks.items()
- s.sort()
- print s # output hand-formatted
- [
- 'AACC': {'id': 'AACC',
- 'others': ['D', '20120127', '4.01', '4.02', '4.03', '4.04', '40000']},
- 'AACOW': {'id': 'AACOW',
- 'others': ['D', '20111207', '0.3', '0.3', '0.3', '0.3', '500']},
- 'AAME': {'id': 'AAME',
- 'others': ['D', '20111207', '1.99', '1.99', '1.95', '1.99', '8600']},
- 'AAON': {'id': 'AAON',
- 'others': ['D', '20111207', '21.62', '21.9', '21.32', '21.49', '93200']},
- 'AAPL': {'id': 'AAPL',
- 'others': ['D','20111207','389.93','390.94','386.76','389.09','10892800']},
- 'B': {'id': 'B',
- 'others': ['D', '20120127', '4.01', '4.02', '4.03', '4.04', '40000']}
- ]