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:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = row[2]
    return my_dict

How can I convert the values in the dictionary into floats?

4
  • float(row[2])? Oct 12, 2018 at 15:12
  • I just ran your code incorporating Matthieu's suggestion on a csv file containing a,1,2.0,3, and it worked perfectly. If it doesn't work on your file, please provide the contents of that file.
    – Kevin
    Oct 12, 2018 at 15:16
  • Would you mind showing us the contents of row[2]? Oct 12, 2018 at 15:17
  • Nevermind, you were right, there was just an error with the compiler.
    – user10454314
    Oct 12, 2018 at 15:19

1 Answer 1

0

Use casting.

There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

Casting in python is therefore done using constructor functions:

int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)

float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)

str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

Reference: https://www.w3schools.com/python/python_casting.asp

What your code should look like:

import csv
def csv_to_kvs(string):
  with open(string) as f:
    my_file = csv.reader(f)
    my_dict = {}
    for row in my_file:
      my_dict[row[0]] = float(row[2])
    return my_dict
1
  • 1
    OP could also use a dictionary comprehension: return {row[0]: float(row[2]) for row in csv.reader(f)} Oct 12, 2018 at 15:22

Your Answer

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