转换csv文件到字典列表

xeufq47z  于 2023-04-03  发布在  其他
关注(0)|答案(8)|浏览(142)

我有一个csv文件

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

我想从这个csv创建一个字典列表。
输出为:

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

我该怎么做?

xjreopfe

xjreopfe1#

使用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)]

将导致:

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

jhiyze9q2#

另一个更简单的答案:

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

7xzttuei3#

使用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

输出:

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

guykilcj4#

很久之后才在这里回答,因为我没有看到任何更新/相关的答案。

df = pd.read_csv('Your csv file path')  
data = df.to_dict('records')
print( data )
sc4hvdpw

sc4hvdpw5#

# 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]
tpgth1q7

tpgth1q76#

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

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))})
pjngdqdw

pjngdqdw7#

将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)
3pmvbmvn

3pmvbmvn8#

我对你的问题的解决方案:

output = []

with open("test.csv", "r") as csv_file:
    data = csv_file.read().split("\n")

text = [data[i].split(",") for i in range(len(data))]

for i in range(1, len(text)) :
    output.append({text[0][num]:text[i][num] for num in range(len(text[i]))})

输出是dico的列表

相关问题