在字典中存储csv数据

时间:2013-11-28 02:10:23

标签: python csv python-3.x dictionary

我正在使用python 3.我在csv文件中有示例数据,我想将其转换为字典:

a.csv中的数据:

a.fruit,a.colour,a.quantity 
apple,red,2 
grapes,purple,4
pear,green,5

我有以下代码:

sample = 'samples.csv'
file_name = open(sample,'r')

reader = csv.DictReader(file_name)
for row in reader:
    print(row)  

当我运行代码时,我得到以下输出:

['a.fruit':'apple','a.colour':'red','a.quantity':'2']
['a.fruit':'grapes','a.colour':'purple','a.quantity':'4']
['a.fruit':'pear','a.colour':'green','a.quantity':'5']

无论如何,我有以下词典:

[{'a.fruit':['apple','grapes','pear'],'a.colour':['red','purple','green'],'a.quantity':['2','4','5'}]

所以dict表示存储在(str:list of str)中(key:value)?

此外,是否可以输出以下内容:  [a:{'a.fruit':['apple','grape','pear'],'a.colour':['red','purple','green'],'a.quantity': [ '2', '4', '5'}]

1 个答案:

答案 0 :(得分:2)

您可以像这样使用list comprehensiondict comprehension

dicts = [row for row in reader]
result = {k:[d[k] for d in dicts] for k in dicts[0].keys()}
print(result)

<强>输出

{'a.fruit': ['apple', 'grapes', 'pear'], 'a.colour': ['red', 'purple', 'green'], 'a.quantity ': ['2 ', '4', '5']}