将多个CSV列中的值返回到Python字典?

时间:2015-04-02 01:53:30

标签: python csv dictionary

我正在尝试将其他CSV列调用到我的Python词典中。

该示例适用于返回一组值(列),但我需要返回彼此不相邻的2列的值。

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

正确返回第3列的值

['9644', '4406', '7643', '2252', '7588']

但是如何从第1列和第3列返回值?

['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'}

3 个答案:

答案 0 :(得分: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]))

答案 1 :(得分:2)

试试这个:

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

输出:

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

答案 2 :(得分: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'}