2015-04-02 38 views
0

我想在下面的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'} 
+0

您是否尝试过** ** csv.DictReader([https://docs.python.org/2/library/csv.html])。有了正确的映射,我认为这将解决您的问题。 – 2015-04-02 02:35:39

+0

是的,但没有。 (你的快捷方式也会返回404) – user1995458 2015-04-02 03:00:33

回答

2

或者试试这个:

import csv 
result={} 
with open('C:/Temp/123.csv') as f: 
    reader = csv.DictReader(f) 
    for row in reader: 
     if row['Status']=='Keep': 
      result.update({row['book_id']:row['book_ref']}) 

这将产生:

{'607842': '9295', '607844': '7643', '607856': '7588'} 
+0

谢谢你对我有用。下面的其他答复值得赞赏,但不涉及'状态'要求。 – user1995458 2015-04-13 00:17:40

2

,你可以简单地尝试这样的:

with open("123.csv") as f: 
    my_list = [] 
    next(f) 
    for x in f: 
     x = x.strip().split() 
     my_list.append((x[0],x[2])) 
2

试试这个:

zipList = zip(*allrows[1:]) 
print dict(zip(zipList[0], zipList[2])) 

输出:

{'607842': '9295', '607856': '7588', '607844': '7643', '607846': '2252'}