读取两列CSV作为字典与第一列作为关键 [英] Read two column CSV as dict with 1st column as key
问题描述
我有一个包含两列的CSV,第一列是专门用于我们项目中特定建筑的团队。
第二列是实际建筑物编号。 / p>
我要找的是以第一列为关键字的字典,以及列表中属于该团队的建筑物。
我尝试了各种形式的 csv.reader
和 csv.DictReader
将数据重写到另一个字典,但我无法得到我想要的结构。
CSV:
team,bldg,
3,204,
3,250,
3,1437,
2,1440,
1,1450,
字典的结构如下:
dict [1] = [1450]
dict [2] = [1440]
dict [3] = [204,250,1437]
它的工作原理:
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']}
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"]
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']}
这篇关于读取两列CSV作为字典与第一列作为关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!