Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the contents of a CSV file into a dictionary

The code I have so far is in a function that basically reads a csv file and prints it's contents:

def read(filename):
    with open(filename, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            print(row)

Contents of sailor.csv:

name, mean performance , std dev
Alice, 100, 0,
Bob, 100, 5,
Clare, 100, 10,
Dennis, 90, 0,
Eva, 90, 5,

read('sailor.csv') and running the function

current output:

['name', ' mean performance ', ' std dev']
['Alice', ' 100', ' 0', '']
['Bob', ' 100', ' 5', '']
['Clare', ' 100', ' 10', '']
['Dennis', ' 90', ' 0', '']
['Eva', ' 90', ' 5', '']

required output:

{'Dennis': (90.0, 0.0), 'Clare':(100.0, 10.0), 
'Eva': (90.0, 5.0), 'Bob': (100.0, 5.0), 'Alice': (100.0, 0.0)}

any ideas how I can achieve that output? Using Python 3.4.2 if that helps, explanation of your answer will be appreciated!

like image 904
Alex Avatar asked Dec 10 '14 04:12

Alex


People also ask

Can a list be converted into a dictionary?

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.

How do I convert a list to a dictionary in Python?

To convert a list to a dictionary using the same values, you can use the dict. fromkeys() method. To convert two lists into one dictionary, you can use the Python zip() function. The dictionary comprehension lets you create a new dictionary based on the values of a list.

What is the method used in file handling to read csv using dictionary?

DictReader() class can be used to read a CSV file as a dictionary.


2 Answers

using the csv standard library and a dictionary comprehension...

import csv
with open('sailor.csv') as csvfile:
   reader = csv.reader(csvfile)
   next(reader)
   d = {r[0] : tuple(r[1:-1]) for r in reader}

Where d will be the dictionary you want. d[1:-1] slices the array from the second to the second to last element.

EDIT: skips headers, converts to tuples

like image 183
Ben Southgate Avatar answered Sep 28 '22 03:09

Ben Southgate


I think this is what you want:

import csv

def read(filename):
    out_dict = {}
    with open(filename, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',')
        next(csvfile) # skip the first row
        for row in reader:
            out_dict[row[0]] = float(row[1]), float(row[2])
            print(row)

    return out_dict

print(read('data.csv'))   

Prints:

{'Bob': (' 100', ' 5'), 'Clare': (' 100', ' 10'), 'Alice': (' 100', ' 0'), 'Dennis': (' 90', ' 0'), 'Eva': (' 90', ' 5')}

Not to much to explain here. Just putting the values in the dictionary, and skipping the first row added. I assumed that the persons names are unique.

like image 37
Marcin Avatar answered Sep 28 '22 05:09

Marcin