0

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}

2
  • "When I submit the following function csv_to_kvs, I get an incorrect input." Please be more specific. When you submit what to csv_to_kvs, with what file contents, you get what? (BTW, did you mean "incorrect output" or "error about incorrect input"? Whichever it is, attach it as well.) Commented Oct 12, 2018 at 4:28
  • store the expected value into a variable. Than write the return statement. your code will return value for first iteration. Commented Oct 12, 2018 at 4:30

3 Answers 3

1

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'}
Sign up to request clarification or add additional context in comments.

1 Comment

meant to tell you earlier , this was a good answer, I learned from it
0

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

2 Comments

Output should convert string as float.
than my_dict[row[0]] = row[2] will be my_dict[row[0]] = float(row[2]).
0
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.