Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

python - 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"]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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']}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...