读取两列CSV作为字典与第一列作为关键 [英] Read two column CSV as dict with 1st column as key

查看:388
本文介绍了读取两列CSV作为字典与第一列作为关键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含两列的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆