Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 804
veena Avatar asked Feb 05 '14 08:02

veena


People also ask

How do I convert a list of dictionaries in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.


Video Answer


3 Answers

Use 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}]
like image 62
falsetru Avatar answered Oct 17 '22 03:10

falsetru


Another simpler answer:

import csv
with open("configure_column_mapping_logic.csv", "r") as f:
    reader = csv.DictReader(f)
    a = list(reader)
    print a
like image 37
Simon Avatar answered Oct 17 '22 03:10

Simon


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}]
like image 10
Ashwini Chaudhary Avatar answered Oct 17 '22 02:10

Ashwini Chaudhary