user8497190
user8497190

Reputation: 21

How to create a list of dictionaries with key:value format from a CSV file using Python?

enter image description here

The want the column headers as the keys without any quotes around them and the subsequent values in the columns as the values of the keys.

This is what I have so far:

import csv

with open('zinc3.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row
        print ("#1\n")

Upvotes: 2

Views: 127

Answers (2)

Mohamed Ali JAMAOUI
Mohamed Ali JAMAOUI

Reputation: 14689

You can use the pandas library in python which can handle:

Here's a general reproducible example (you need to install pandas)

from StringIO import StringIO 
import pandas as pd 

data = """
col1|col2
1|2
21|2
14|2
12|42
10|2
1|27
""" 

# StringIO(data) to simulate a csv file 
# replace it with the name of your csv file 
df = pd.read_csv(StringIO(data), sep="|")

print(df.to_dict(orient="records"))

The output looks like this:

[{'col2': 2, 'col1': 1}, {'col2': 2, 'col1': 21}, {'col2': 2, 'col1': 14}, {'col2': 42, 'col1': 12}, {'col2': 2, 'col1': 10}, {'col2': 27, 'col1': 1}]

For your specific case, you need to do the following

import pandas as pd 
df = pd.read_csv("zinc3.csv", sep="|")    
print(df.to_dict(orient="records"))

Upvotes: 1

pylang
pylang

Reputation: 44525

If I understand you correctly, given a file:

# test.csv
1,2,3
a_foo,b_foo,c_foo
a_bar,b_bar,c_bar

You can make a dictionary with numeric headings as follows:

import csv
import collections as ct


with open("./test.csv") as f:
    reader = csv.DictReader(f)
    dd = ct.defaultdict(list)
    for row in reader:
        for k, v in row.items():
            dd[int(k)].append(v)
dd

Output

defaultdict(list,
            {1: ['a_foo', 'a_bar'],
             2: ['b_foo', 'b_bar'],
             3: ['c_foo', 'c_bar']})

You will have to replace the filename. The DictReader yields a dictionary for each row, where the keys are the headers and the values are the subsequent items from each column. Here we rebuild the dictionary by appending values to a defaultdict. The keys (assumed numeric) are converted to integers.


For small files, you can condense this code with a list comprehension:

with open("./test.csv") as f:
    reader = csv.DictReader(f)
    dd = ct.defaultdict(list)
    [dd[int(k)].append(v) for row in reader for k, v in row.items()]

dd

Upvotes: 0

Related Questions