在Python中读取csv文件并创建一个字典

时间:2015-07-05 18:47:06

标签: python csv dictionary

我正在尝试在python 27中读取csv文件来创建字典。 CSV文件看起来像 -

  

SI1440269,SI1320943,SI1321085   SI1440270,SI1320943,SI1321085,SI1320739   SI1440271,SI1320943
  SI1440273,SI1321058,SI1320943,SI1320943

每行中的条目数不固定。第一列条目应该是我的密钥。我的代码 -

SELECT 
    CASE
       WHEN a >= b AND a >= c THEN a 
       WHEN b >= a AND b >= c THEN b 
       ELSE c  
    END AS a,
    CASE
       WHEN b >= c AND a >= b THEN b 
       WHEN b >= a AND c >= b THEN b 
       WHEN c >= a AND b >= c THEN c 
       WHEN c >= b AND a >= c THEN c 
       ELSE a 
    END AS b, 
    CASE 
       WHEN b >= c AND a >= c THEN c 
       WHEN a <= c AND a <= b THEN a 
       ELSE b 
    END AS c

输出:

  

{&#39; SI1440273&#39;:[&#39; SI1321058&#39;,&#39; SI1320943&#39;,&#39; SI1320943&#39;],&#39;&#39; :[&#39;&#39;&#39;&#39;,&#39;&#39;],&#39; SI1440271&#39;:[&#39; SI1320943&#39;,& #39;&#39;,&#39;&#39;],&#39; SI1440270&#39;:[&#39; SI1320943&#39;,&#39; SI1321085&#39;,&#39; SI1320739&#39;],&#39; SI1440269&#39;:[&#39; SI1320943&#39;,&#39; SI1321085&#39;,&#39;&#39;]}

如何摆脱输出中的空值? 另外,如何让输出中的键值与csv文件中的键值相同?

编辑: 我想要单行按键&#39;

3 个答案:

答案 0 :(得分:3)

您可以使用csv.DictReader,如下所示:

import csv

result = {}
with open('test.csv') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=" ", fieldnames=["id"], restkey="data")
    for row in reader:
        print row
        result[row["id"]] = row["data"]

print result

这将为您提供每行字典解决方案,因此您可以一次处理一行。然后我还将它们全部附加到一个result字典中。

从这里你将得到以下输出:

{'data': ['SI1320943', 'SI1321085'], 'id': 'SI1440269'}
{'data': ['SI1320943', 'SI1321085', 'SI1320739', 'SI1440271', 'SI1320943'], 'id': 'SI1440270'}
{'data': ['SI1321058', 'SI1320943', 'SI1320943'], 'id': 'SI1440273'}
{'SI1440273': ['SI1321058', 'SI1320943', 'SI1320943'], 'SI1440270': ['SI1320943', 'SI1321085', 'SI1320739', 'SI1440271', 'SI1320943'], 'SI1440269': ['SI1320943', 'SI1321085']}

答案 1 :(得分:3)

试试这个

import csv
reader = csv.reader(open('test.csv'))

result = {row[0]:row[1:] for row in reader if row and row[0]}
print result

如果你想进一步消除值中的null,那么请按照

进行操作
import csv
reader = csv.reader(open('test.csv'))

result = {row[0]:[i for i in row[1:] if i] for row in reader if row and row[0]}
print result

保留录取顺序

from collections import OrderedDict
result = OrderedDict()
for row in reader:
   if row and row[0]:
      result[row[0]]=[i for i in row[1:] if i]

# print result
for key in result:
   print key,":" ,result[key]

答案 2 :(得分:2)

如前所述,这不是CSV - 所以readline和split更合适,并使用OrderedDict来保持输入顺序:

import csv
from collections import OrderedDict
result = OrderedDict()
with open('test.csv') as f:
    for row  in f:
        row=row.strip().split()
        key = row[0]
        result[key] = row[1:]
print result