Moon47
Moon47

Reputation: 103

Read two column CSV as dict with 1st column as key

I have a CSV with two columns, column one is the team dedicated to a particular building in our project.

The second column is the actual building number.

What I am looking for is a dictionary with the first column as the key and the buildings that belong to that team in the list.

I have tried various forms of csv.reader and csv.DictReader along with different for loops to rewrite the data to another dictionary, but I cannot get the structure I want.

CSV:

team,bldg,
3,204,
3,250,
3,1437,
2,1440,
1,1450,

The structure of the dictionary would be as follows:

dict["1"] = ["1450"]
dict["2"] = ["1440"]
dict["3"] = ["204", "250", "1437"]

Upvotes: 4

Views: 6179

Answers (2)

dawg
dawg

Reputation: 103884

This works:

import csv

result={}
with open('/tmp/test.csv','r') as f:
    red=csv.DictReader(f)
    for d in red:
        result.setdefault(d['team'],[]).append(d['bldg'])

#results={'1': ['1450'], '3': ['204', '250', '1437'], '2': ['1440']}

Upvotes: 5

mechanical_meat
mechanical_meat

Reputation: 169354

The useful collections.defaultdict in the standard library makes short work of this task:

import csv
import collections as co

dd = co.defaultdict(list)
with open('/path/to/your.csv'),'rb') as fin:
    dr = csv.DictReader(fin)
    for line in dr:
        dd[line['team']].append(line['bldg'])

# defaultdict(<type 'list'>, {'1': ['1450'], '3': ['204', '250', '1437'], '2': ['1440']})

http://docs.python.org/2/library/collections.html#collections.defaultdict

The first argument provides the initial value for the default_factory attribute; it defaults to None.

Upvotes: 2

Related Questions