python csv到字典列 [英] python csv to dictionary columnwise

查看:140
本文介绍了python csv到字典列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将csv文件中的数据读取到字典中,使得一列的第一行是键,而同一列的其余行构成该值作为列表?

Is it possible to read data from a csv file into a dictionary, such that the first row of a column is the key and the remaining rows of that same column constitute the value as a list?

例如我有一个csv文件

E.g. I have a csv file

     strings, numbers, colors 
     string1, 1, blue
     string2, 2, red
     string3, 3, green
     string4, 4, yellow

使用

with open(file,'rU') as f: 
    reader = csv.DictReader(f)
    for row in reader:
        print row

我获得

{'color': 'blue', 'string': 'string1', 'number': '1'}
{'color': 'red', 'string': 'string2', 'number': '2'}
{'color': 'green', 'string': 'string3', 'number': '3'}
{'color': 'yellow', 'string': 'string4', 'number': '4'}

或使用

 with open(file,'rU') as f: 
        reader = csv.reader(f)
        mydict = {rows[0]:rows[1:] for rows in reader}
        print(mydict)

我得到以下字典

{'string3': ['3', 'green'], 'string4': ['4', 'yellow'], 'string2': ['2', 'red'], 'string': ['number', 'color'], 'string1': ['1', 'blue']}

但是,我会喜欢获得

{'strings': ['string1', 'string2', 'string3', 'string4'], 'numbers': [1, 2, 3,4], 'colors': ['red', 'blue', 'green', 'yellow']}


推荐答案

您需要解析第一行,创建列,然后进行到其余行。

You need to parse the first row, create the columns, and then progress to the rest of the rows.

例如:

columns = []
with open(file,'rU') as f: 
    reader = csv.reader(f)
    for row in reader:
        if columns:
            for i, value in enumerate(row):
                columns[i].append(value)
        else:
            # first row
            columns = [[value] for value in row]
# you now have a column-major 2D array of your file.
as_dict = {c[0] : c[1:] for c in columns}
print(as_dict)

输出:

{
    ' numbers': [' 1', ' 2', ' 3', ' 4'], 
    ' colors ': [' blue', ' red', ' green', ' yellow'],
    'strings': ['string1', 'string2', 'string3', 'string4']
}

(有些怪异在输入文件中的空格。请删除逗号前后的空格,如果实际输入中有空格,请使用 value.strip()。)

(some weird spaces, which were in your input "file". Remove spaces before/after commas, or use value.strip() if they're in your real input.)

这篇关于python csv到字典列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆