Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

csv

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"]
like image 206
Moon47 Avatar asked Oct 18 '25 17:10

Moon47


1 Answers

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']}
like image 70
dawg Avatar answered Oct 20 '25 08:10

dawg