csv文件到字典

时间:2016-12-08 17:19:47

标签: python csv dictionary

我想从csv文件写入字典。

可是:

  1. 行中的第一个单词应该是键
  2. 该行中的所有其他字词应为此键的单独值。
  3. 到目前为止我的代码:

    def coordinates(text):
        import csv
        reader = csv.reader(open(text))
        d = {}
    
        for row in reader:
            key = row[0]
            d[key] = row[1:]
        print(d)
    
    coordinates('luchthavens2.csv')
    

    使用此代码,行中的所有项目都是我字典中的键。

    谁可以提供帮助?

    编辑:

    输入文件如下所示:

    BIN,"Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\N,\N,1149361
    BST,"Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\N,1134720,1149361
    CCN,"Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\N,\N,1149361
    

    所有来自名为luchthavens2.csv的excel文件,文本的位置是A1-A2-A3等。

    你应该在这里找到它:https://expirebox.com/download/bb8cb3a39f9be041743a8b86db89093b.html

    输出:

    {
    'CCN,"Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\\N,\\N,1149361': [],
    'BST,"Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\\N,1134720,1149361': [],
    'BIN,"Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\\N,\\N,1149361': []
    }
    

    编辑:

    我已将输入文件更改为文本文件,然后再将其更改为csv文件。奇怪的是,这有效,我可以毫无问题地阅读它。

3 个答案:

答案 0 :(得分:1)

如果您运行以下内容,

import pprint
import csv


def coordinates(text):
    ret = {}
    with open(text, 'r') as fp:
        reader = csv.reader(fp)
        for row in reader:
            key = row.pop(0)
            ret[key] = row
    return ret


data = coordinates('data.csv')
pprint.pprint(data)

在以下文件中

$ cat data.csv 
AAA,"Blub",25.25
BBB,"Blob",27.27

然后你会得到,

$ python stackoverflow.py 
{'AAA': ['Blub', '25.25'], 'BBB': ['Blob', '27.27']}

答案 1 :(得分:1)

在输入文件中,引号混乱。

"BIN,""Bamiyan"",""Bamiyan"",""Afghanistan"",""AF"",34.800000,67.816667,701,""Afghanistan"",\N,\N,1149361"
"BST,""Bost"",""Bost"",""Afghanistan"",""AF"",31.550000,64.366667,701,""Afghanistan"",\N,1134720,1149361"
"CCN,""Chakcharan"",""Chakcharan"",""Afghanistan"",""AF"",34.533333,65.266667,701,""Afghanistan"",\N,\N,1149361"

应该是

"BIN","Bamiyan","Bamiyan","Afghanistan","AF",34.800000,67.816667,701,"Afghanistan",\N,\N,1149361
"BST","Bost","Bost","Afghanistan","AF",31.550000,64.366667,701,"Afghanistan",\N,1134720,1149361
"CCN","Chakcharan","Chakcharan","Afghanistan","AF",34.533333,65.266667,701,"Afghanistan",\N,\N,1149361

答案 2 :(得分:0)

这应该给你想要的输出。 您的数据格式不正确

import csv
reader = csv.reader(open('luchthavens2.csv'))
d = {}

for row in reader:
    row = row[0].split(',')
    key = row[0]
    d[key] = row[1:]

相反,您不需要CSV模块,因为您的数据不是正确的CSV

下面的代码将解决您没有CSV模块的问题

d = dict()
with open('luchthavens2.csv') as fh:
    for row in fh:
        row = row.split(',')
        key = row[0]
        d[key] = row[1:]