Python 将csv文件转换为字典列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21572175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:10:13  来源:igfitidea点击:

convert csv file to list of dictionaries

pythonlistcsvdictionary

提问by veena

I have a csv file

我有一个 csv 文件

col1, col2, col3
1, 2, 3
4, 5, 6

I want to create a list of dictionary from this csv.

我想从这个 csv 创建一个字典列表。

output as :

输出为:

a= [{'col1':1, 'col2':2, 'col3':3}, {'col1':4, 'col2':5, 'col3':6}]

How can I do this?

我怎样才能做到这一点?

采纳答案by falsetru

Use csv.DictReader:

使用csv.DictReader

import csv

with open('test.csv') as f:
    a = [{k: int(v) for k, v in row.items()}
        for row in csv.DictReader(f, skipinitialspace=True)]

Will result in :

将导致:

[{'col2': 2, 'col3': 3, 'col1': 1}, {'col2': 5, 'col3': 6, 'col1': 4}]

回答by Ashwini Chaudhary

Using the csvmodule and a list comprehension:

使用csv模块和列表理解:

import csv
with open('foo.csv') as f:
    reader = csv.reader(f, skipinitialspace=True)
    header = next(reader)
    a = [dict(zip(header, map(int, row))) for row in reader]
print a    

Output:

输出:

[{'col3': 3, 'col2': 2, 'col1': 1}, {'col3': 6, 'col2': 5, 'col1': 4}]

回答by user3030010

Well, while other people were out doing it the smart way, I implemented it naively. I suppose my approach has the benefit of not needing any external modules, although it will probably fail with weird configurations of values. Here it is just for reference:

好吧,当其他人以聪明的方式去做时,我却天真地实施了它。我想我的方法的好处是不需要任何外部模块,尽管它可能会因奇怪的值配置而失败。这里仅供参考:

a = []
with open("csv.txt") as myfile:
    firstline = True
    for line in myfile:
        if firstline:
            mykeys = "".join(line.split()).split(',')
            firstline = False
        else:
            values = "".join(line.split()).split(',')
            a.append({mykeys[n]:values[n] for n in range(0,len(mykeys))})

回答by MOCKBA

# similar solution via namedtuple:    

import csv
from collections import namedtuple

with open('foo.csv') as f:
  fh = csv.reader(open(f, "rU"), delimiter=',', dialect=csv.excel_tab)
  headers = fh.next()
  Row = namedtuple('Row', headers)
  list_of_dicts = [Row._make(i)._asdict() for i in fh]

回答by Mitul Panchal

Simple method to parse CSV into list of dictionaries

将 CSV 解析为字典列表的简单方法

with open('/home/mitul/Desktop/OPENEBS/test.csv', 'rb') as infile:
  header = infile.readline().split(",")
  for line in infile:
    fields = line.split(",")
    entry = {}
    for i,value in enumerate(fields):
      entry[header[i].strip()] = value.strip()
      data.append(entry)

回答by Simon

Another simpler answer:

另一个更简单的答案:

    import csv
    with open("configure_column_mapping_logic.csv", "r") as f:
        reader = csv.DictReader(f)
        a = list(reader)
        print a

回答by parovelb

To convert a CSV file (two columns, multiple rows, no header) to a list of dictionaries, I used the csv module. My csv file looked like this:

要将 CSV 文件(两列、多行、无标题)转换为字典列表,我使用了csv 模块。我的 csv 文件如下所示:

c1,-------- 
c14,EAE23ED3 
c15,-------- 

I wanted to create a list of dictionaries, each row of the csv file to be a dictionary (key, value pair). The output I wanted was:

我想创建一个字典列表,csv 文件的每一行都是一个字典(键,值对)。我想要的输出是:

[
{
    "c1": "--------"
}, 
{
    "c14": "EAE23ED3"
}, 
{
    "c15": "--------"
}
]

To do this I used the code below:

为此,我使用了以下代码:

import csv

csv_path = '.../input_file.csv'

mylist = []
mydict = {}

# read the csv and write to a dictionary
with open(csv_path, 'rb') as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        mydict = {row[0]:row[1]}
        mylist.append(mydict)

print(mylist)

It works in my case. To solve my problem, these posts were helpful:

它适用于我的情况。为了解决我的问题,这些帖子很有帮助: