使用python从CSV创建字典 [英] Creating a dictionary from CSV using python

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

问题描述

我有一个CSV格式

其中A,B& C是标题.

where A, B & C are the headers.

我如何将该CSV Python转换为以下形式的字典

How do I pythonically convert this CSV into a dictionary of the following form

{'A': '1', 'B': '4','C': '7'},
{'A': '2', 'B': '5','C': '8'},
{'A': '3', 'B': '6','C': '9'}

到目前为止,我正在尝试以下代码:

So far I'm trying the following code:

import csv
reader = csv.DictReader(open('file.csv'))

result = {}
for row in reader:
    for column, value in row.items():
        result.setdefault(column, []).append(value)

这没有给我预期的输出.有什么建议吗?

This is not giving me the intended output. Any suggestions?

推荐答案

您没有多余的代码. csv已经为您完成了繁重的工作.只需按原样使用csv.DictReader:

The extra code you have is unnecessary. csv already does the heavy-lifting for you. Just use csv.DictReader as is:

import csv

with open('e.txt') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

以上输出:

OrderedDict([('A', '1'), (' B', ' 4'), (' C', ' 7')])
OrderedDict([('A', '2'), (' B', ' 5'), (' C', ' 8')])
OrderedDict([('A', '3'), (' B', ' 6'), (' C', ' 9')])    

您可能认为您想要的是dict而不是OrderedDict,但是我很确定您不需要.使用OrderedDict对象将确保您的行保持正确的顺序.

You may think you want a dict rather than an OrderedDict, but I'm fairly sure you don't. Using an OrderedDict object will ensure that your rows stay ordered correctly.

感谢您的答复.这似乎可行,但是对于我的任务,我需要使用问题中提到的格式.有没有办法将其转换为这种格式?

thank you for your reply. This seems to work but for my task, I need it in the format mentioned in the question. Is there a way to turn it into that format?

为什么呢?不要被格式所迷惑. OrderedDict 具有与常规词典相同的完全 .唯一的区别是OrderedDict将保持其顺序.如果只需要以某种格式打印行,则可以将每行转换为dict并使用它的__repr__:

Why exactly? Don't be fooled by the format. OrderedDict behaves the exact same as a normally dictionary. The only difference is that OrderedDict will maintain its order. If all you need is to print your rows in a certain format, you can convert each row to a dict and use it's __repr__:

for row in reader:
    print(dict(row))

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

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