我想在下面的Python字典中调用额外的CSV列。将多个CSV列的值返回给Python字典?
该示例适用于返回一组值(列),但我需要返回不相邻的2列的值。从正确
['9644', '4406', '7643', '2252', '7588']
但如何从列1和3返回值3列
import csv
# set csv file and path
allrows=list(csv.reader(open('C:/Data/Library/Peter/123.csv')))
# Extract the first row as keys for a columns dictionary
columns=dict([(x[0],x[1:]) for x in zip(*allrows)])
# Then extracting column 3 from all rows with a certain criterion in column 4
matchingrows=[rownum for (rownum,value) in enumerate(columns['Status']) if value == 'Keep']
print map(columns['book_ref'].__getitem__, matchingrows)
**sample from 123.csv**
book_id TYPE book_ref Status
607842 3 9295 Keep
607844 4 7643 Keep
607846 3 2252 Retire
607856 3 7588 Keep
返回值?
['607842':'4406', '607844':'7643', '607846':'2252', '607856':'7588']
我也试过这个,但是我没有得到我想要的东西。
##import csv
##with open('C:/Data/Library/Peter/123.csv') as f:
## reader = csv.DictReader(f)
## for row in reader:
## print row
'''
{'Status': 'Retire', 'TYPE': '3', 'book_ref': '2397', 'book_id': '607838'}
{'Status': 'Keep', 'TYPE': '12', 'book_ref': '9644', 'book_id': '607839'}
{'Status': 'Retire', 'TYPE': '4', 'book_ref': '9295', 'book_id': '607841'}
{'Status': 'Keep', 'TYPE': '3', 'book_ref': '4406', 'book_id': '607842'}
{'Status': 'Retire', 'TYPE': '4', 'book_ref': '1798', 'book_id': '607843'}
{'Status': 'Keep', 'TYPE': '4', 'book_ref': '7643', 'book_id': '607844'}
{'Status': 'Retire', 'TYPE': '3', 'book_ref': '6778', 'book_id': '607845'}
{'Status': 'Keep', 'TYPE': '3', 'book_ref': '2252', 'book_id': '607846'}
{'Status': 'Retire', 'TYPE': '4', 'book_ref': '7910', 'book_id': '607855'}
{'Status': 'Keep', 'TYPE': '3', 'book_ref': '7588', 'book_id': '607856'}
您是否尝试过** ** csv.DictReader([https://docs.python.org/2/library/csv.html])。有了正确的映射,我认为这将解决您的问题。 – 2015-04-02 02:35:39
是的,但没有。 (你的快捷方式也会返回404) – user1995458 2015-04-02 03:00:33