0

Suppose I have a csv file and want a dictionary with multiple keys per value.

example csv:

col1,col2,col2,col4,col5
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
a3,b3,c3,d3,e3

How would you go about creating a dictionary, such that you extract specifically columns 1,2,3 as the keys and use col5 as the value.

Output:

{(a1,b1,c1):e1 , (a2,b2,c2):e2 , (a3,b3,c3):e3 }

Are there methods that help do this?

2 Answers 2

5

You can use a dict comprehension:

import csv

with open(filename, 'rb') as infh:
    reader = csv.reader(infh)
    next(reader)  # skip the header row
    result = {tuple(row[:3]): row[4] for row in reader}

Keys for a dictionary must be immutable; the csv.reader() produces lists so to produce a tuple from the first 3 columns I used a slice and the tuple() function.

Demo:

>>> import csv
>>> sample = '''\
... col1,col2,col2,col4,col5
... a1,b1,c1,d1,e1
... a2,b2,c2,d2,e2
... a3,b3,c3,d3,e3
... '''
>>> reader = csv.reader(sample.splitlines())
>>> next(reader)
['col1', 'col2', 'col2', 'col4', 'col5']
>>> {tuple(row[:3]): row[4] for row in reader}
{('a3', 'b3', 'c3'): 'e3', ('a2', 'b2', 'c2'): 'e2', ('a1', 'b1', 'c1'): 'e1'}
3

You need to use a tuple for the dictionary key. Adapting from csv module documentation, the following should work.

import csv

with open('eggs.csv') as csvfile:
    spamreader = csv.reader(csvfile)

    next(spamreader) # skip header
    results = { (a, b, c): e for a, b, c, d, e in spamreader }
    # or for python <= 2.6
    # results = dict(((a, b, c), e) for a, b, c, d, e in spamreader)

print(results)

prints out

{('a3', 'b3', 'c3'): 'e3', ('a2', 'b2', 'c2'): 'e2', ('a1', 'b1', 'c1'): 'e1'}
4
  • rather than writing " for a,b,c,d,e in ", can you save the entire header, like this: header = next(spamreader), and then replace the a,b,c,d,e? Jul 30, 2014 at 15:20
  • 1
    yes, and no; you could store the header and then make a dictionary... but it would not help here. Jul 30, 2014 at 15:25
  • Do you know why I'm getting a syntax error on the for loop? Jul 30, 2014 at 15:37
  • 2
    because you are using python 2.6 Jul 30, 2014 at 15:40

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