7

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!

5 Answers 5

8

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

2
  • What about the first row: ['name', ' mean performance ', ' std dev']?
    – Marcin
    Commented Dec 10, 2014 at 4:24
  • This is close, but the numbers are meant to be in tuples I think? like so: 'Eva': (90.0, 5.0) not 'Eva': [90.0, 5.0]. And 'name': [' mean performance '] is also printed
    – Alex
    Commented Dec 10, 2014 at 4:30
2

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.

3
  • His required output has floating point numbers; or maybe it is just ".0" added. And there are no quote marks around the numbers. Commented Dec 10, 2014 at 4:37
  • I tweaked it slightly, adding float before row[1] and row[2] fixed the numbers.. now it works perfectly! Thanks! - no need to use print either as I'll be calling the function later.. read('sailor.csv') works for me!
    – Alex
    Commented Dec 10, 2014 at 5:16
  • @Alex FYI, if you make an edit suggestion, you should provide a more detailed description on why you did the edit (rather than what you edited)... You don't get to see the comments in the Suggested Edits review; only the post with changes, and the reason you provide; see this meta post ... You also shouldn't change your question to include the accepted answer; you click "accept" on a question to do that, this keeps the question "clean" for future people with a similar problem who end up here. Commented Dec 10, 2014 at 6:46
2

So... I know this question has mostly been answered, but I thought I'd just throw a one-liner in the mix to add on to the shortening answers:

from csv import reader
from itertools import islice

{r[0] : tuple(r[1:-1]) for r in islice(reader(open('sailor.csv')), 1, None)}

The only really novel thing is adding islice to skip the header row cleanly.

1
  • one thing you missed is making the numbers floats, other than that nice :)
    – Alex
    Commented Dec 10, 2014 at 5:54
0

Use DictReader:

def read(filename):
    with open(filename, 'r') as csvfile:
        reader = csv.DictReader(csvfile, delimiter=',')
        for row in reader:
            print(row)
1
  • 1
    wont each row be {"header1" : val1, "header2" : val2,...} instead of the tuple / list as shown above? Commented Dec 10, 2014 at 4:17
0

Here is my solution if I may:

>>> import pyexcel as pe
>>> s = pe.load("sailor.csv", name_rows_by_column=0, name_columns_by_row=0)
>>> s.format(float)
>>> s
Sheet Name: csv
+--------+------------------+---------+---+
|        | mean performance | std dev |   |
+========+==================+=========+===+
| Alice  | 100              | 0       | 0 |
+--------+------------------+---------+---+
| Bob    | 100              | 5       | 0 |
+--------+------------------+---------+---+
| Clare  | 100              | 10      | 0 |
+--------+------------------+---------+---+
| Dennis | 90               | 0       | 0 |
+--------+------------------+---------+---+
| Eva    | 90               | 5       | 0 |
+--------+------------------+---------+---+
>>> del s.column[''] # delete the column which has '' as its name
>>> s.to_dict(True) # make a dictionary using row names as key
OrderedDict([('Alice', [100.0, 0.0]), ('Bob', [100.0, 5.0]), 
('Clare', [100.0, 10.0]), ('Dennis', [90.0, 0.0]), ('Eva', [90.0, 5.0])])

Here is the documentation on pe.load and to_dict of pyexcel

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.