将.csv表转换为字典 [英] Convert .csv table to dictionary

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

问题描述

所以我有以下格式的几个csv文件:

So I have a few csv files in in the following format:

person,age,nationality,language
Jack,18,Canadian,English
Rahul,25,Indian,Hindi
Mark,50,American,English
Kyou, 21, Japanese, English

我需要导入它,并将该数据作为字典返回,键作为第一行的列标题,所有数据作为该特定键的值。例如:

I need to import that, and return that data as a dictionary, with the keys as the column headings in the first row, and all the data in each column as values for that specific key. For example:

dict = {
    'person': ['Jack', 'Rahul', 'Mark', 'Kyou'],
    'age': [18, 25, 50, 21],
    'nationality': ['Canadian', 'Indian', 'American', 'Japanese'],
    'language': ['English', 'Hindi', 'English', 'English']
}

任何想法我将如何开始这个代码,使它的代码适用于.csv文件中给定的任意数量的列?

Any idea how I would begin this code and make it so that the code would work for any number of columns given in a .csv file?

推荐答案

这里是一个相当简单的解决方案,使用python CSV模块(DOCs这里: http://docs.python.org/2/library/csv.html )。只需将'csv_data.csv'替换为您的CSV文件的名称。

Here is a fairly straightforward solution that uses the python CSV module (DOCs here: http://docs.python.org/2/library/csv.html). Just replace 'csv_data.csv' with the name of you CSV file.

import csv

with open('csv_data.csv') as csv_data:
    reader = csv.reader(csv_data)

    # eliminate blank rows if they exist
    rows = [row for row in reader if row]
    headings = rows[0] # get headings

    person_info = {}
    for row in rows[1:]:
        # append the dataitem to the end of the dictionary entry
        # set the default value of [] if this key has not been seen
        for col_header, data_column in zip(headings, row):
            person_info.setdefault(col_header, []).append(data_column)

    print person_info

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

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