簡體   English   中英

將特定列值作為鍵讀取csv到字典

[英]Read a csv to dictionary with particular column value as key

我正在嘗試將CS​​V讀入python的字典中

Name    Value    time  count
sample  A        00:00  45
sample  A        01:00  46
sample  A        02:00  50
sample  A        03:00  85
sample  A        04:00  87
abb     B        00:00  40
abb     B        01:00  55

我希望輸出為:

{ A:[{time:00:00 ,count:45},{time:01:00,count:46},{time:02:00,count:50}]}

有人可以幫我獲得輸出嗎?

我嘗試了dict理解,我能夠將csv讀取為字典,其中鍵作為列標題,值作為行,但不確定如何獲取上述輸出。

讀入文件,然后拆分為抽象鍵和值

with open(file,'rb') as f:
 res = {}
 reader  = csv.reader(f)
 for i,line in enumerate(reader):
   if i == 0: continue 
   keyWord = line.split(' ')[1]
   timeKeyword  = 'time:' + line.split(' ')[2]
   countValue = line.split(' ')[3]
   res[keyWord ] = res.get(keyWord,[]) + [{timeKeyword : int(countValue )}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM