簡體   English   中英

Python 逐行讀取文件並轉換為字典

[英]Python read file line by line and convert to dictionary

我在 file.sec 中有以下數據:

goog,100
goog,101
goog,103
micro,200
micro,201
face,99

我想將此數據轉換為字典: {'goog': [100,101,103], 'micro': [200, 201], 'face': [99]}

我嘗試了下面的代碼,但是每當值從 goog 更改為 micro 時它就會清除列表,我得到的結果是:{'goog': [99], 'micro': [99], 'face':[99]}

allD = {}
allN = []
f = open('file.sec' , 'r')
for data in f:
   com = data.split(',')[0]
   
   if com not in allD.keys():
      del allN[:]

   allN.append( data.split(',')[1] )

   allD[ com ] = allN  
    
 print allD        

你可以使用defaultdict

from collections import defaultdict

result = defaultdict(list)

f = open('file.sec' , 'r')
for data in f:
    com = data.split(',')[0]
    result[com].append(data.split(',')[1]

您可以使用 defaultdict 來解決此問題:

from collections import defaultdict

data_dict = defaultdict(list)

f = open('file.sec' , 'r')
for data in f:
    key, value = data.split(',')
    data_dict[key].append(value)

請注意,我是用 python 3 語法編寫的,因此您可能需要對 python 2 稍作不同的處理。

您不遠,但對 Python 分配是什么存在誤解。 當您編寫allD[ com ] = allN時, allD[com]不是allN的副本,而只是對相同 object 的另一個引用。 因此,當您稍后使用del allN[:]清理allN時,您實際上清理了最后一個allD[com] 您應該改用新的 object:

allD = {}
allN = []
f = open('file.sec' , 'r')
for data in f:
   com = data.split(',')[0]
   
   if com not in allD.keys():
      allN = []
      allD[ com ] = allN  

   allN.append( data.split(',')[1] )

    
 print allD

一個沒有 defaultdict 的例子:

allD = {}
allN = []
f = open('data.csv', 'r')
for data in f:
    com = data.split(',')[0]

    if com not in allD.keys():
        allD[com] = []

    allD[com].append(data.split(',')[1].strip())

print(allD)

暫無
暫無

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

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