user10454314
user10454314

Reputation:

Difficulty with csv reading file

Write a function named "csv_to_kvs" that takes a string as a parameter representing the name of a CSV file with 4 columns in the format "string, float, float, float" and returns a new key-value store mapping strings to floating point numbers. The returned key-value store will have one pair for each row in the file with keys from the first column of the CSV file and values from the third column. (My code below)

import csv
def csv_to_kvs(string):
    with open(string) as f:
        file = csv.DictReader(f)
        for column in file:
            for key in column.keys():
                return key
             for value in column.values():
                return value

When I submit the following function csv_to_kvs, I get an incorrect input.

input experienced.csv:

spite,-11.09,3.92,7.38
questionnaire,12.8,-4.39,-0.14
literally,19.5,-3.94,-5.06
colleague,17.19,-15.3,0.12

returned: "spite"

expected: {'colleague': -15.3, 'spite': 3.92, 'questionnaire': -4.39, 'literally': -3.94}

Upvotes: 0

Views: 582

Answers (3)

Hrishikesh
Hrishikesh

Reputation: 25

Python Pandas is a great library to read and write CSV files

* Read CSV file - 

import pandas as pd
data = pd.read_csv("filename.csv")
data.head()

* Write CSV file - 

import pandas as pd
result = {Any key value pair data}
df = pd.DataFrame(data=result)
df.to_csv(filepath.csv, sep='\t', encoding='utf-8')

Upvotes: 0

blhsing
blhsing

Reputation: 107040

csv.DictReader expects your headers to be the columns of the first row, not the rows of the first column.

You should instead use csv.reader to read the rows, transpose it with zip to unpack the first item as headers and the rest as data, and then use list comprehension to construct a list of dict:

with open(string) as f:
    headers, *data = zip(*csv.reader(f))
    l = [{header: item for header, item in zip(headers, lst)} for lst in data]

With your sample input, l would become:

[{'spite': '-11.09', 'questionnaire': '12.8', 'literally': '19.5', 'colleague': '17.19'}, {'spite': '3.92', 'questionnaire': '-4.39', 'literally': '-3.94', 'colleague': '-15.3'}, {'spite': '7.38', 'questionnaire': '-0.14', 'literally': '-5.06', 'colleague': '0.12'}]

and the third column would be simply l[1]:

{'spite': '3.92', 'questionnaire': '-4.39', 'literally': '-3.94', 'colleague': '-15.3'}

Upvotes: 1

R.A.Munna
R.A.Munna

Reputation: 1709

you can use csv.reader(). which can help you to read the row as a list.

import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
     # as you want to key value as the first one and value will be third one
       my_dict[row[0]] = row[2]
    return my_dict

Ouput: {'spite': '3.92', 'questionnaire': '-4.39', 'literally': '-3.94', 'colleague': '-15.3'}

Upvotes: 0

Related Questions