简体   繁体   中英

convert csv file to list of dictionaries

I have a csv file

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

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

output as :

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

How can I do this?

Usecsv.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}]

Another simpler answer:

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

Using the csv module and a list comprehension:

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

Answering here after long time as I don't see any updated/relevant answers.

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

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

Simple method to parse CSV into list of dictionaries

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)

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:

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:

[
{
    "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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM