4

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"]
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Moon47
  • 103
  • 2
  • 11

2 Answers2

5

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']}
dawg
  • 98,345
  • 23
  • 131
  • 206
2

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.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223