2012-12-05 8 views
1

我有一個情況我有一個文本文件中讀取字典中,從特定格式的另一個列表特定格式如何有通過列表追加多個值,目前我有一個問題,我無法通過正常</p> <p>認爲

(捕食)吃(獵物)

什麼,我試圖做的就是把它變成一本字典但有些情況下也有多個行的情況。

(捕食)吃(獵物)

如果同一捕食者顯示出來吃不同的獵物。

到目前爲止,這是什麼樣子......

import sys 


predpraydic={}#Establish universial dictionary for predator and prey 
openFile = open(sys.argv[1], "rt") # open the file 

data = openFile.read() # read the file 
data = data.rstrip('\n') #removes the empty line ahead of the last line of the file 
predpraylist = data.split('\n') #splits the read file into a list by the new line character 




for items in range (0, len(predpraylist)): #loop for every item in the list in attempt to split the values and give a list of lists that contains 2 values for every list, predator and prey 
    predpraylist[items]=predpraylist[items].split("eats") #split "eats" to retrive the two values 
    for predpray in range (0, 2): #loop for the 2 values in the list 
     predpraylist[items][predpray]=predpraylist[items][predpray].strip() #removes the empty space caued by splitting the two values 
for items in range (0, len(predpraylist) 
    if 


for items in range (0, len(predpraylist)): # Loop in attempt to place these the listed items into a dictionary with a key of the predator to a list of prey 
    predpraydic[predpraylist[items][0]] = predpraylist[items][1] 

print(predpraydic) 
openFile.close() 

正如你看到的,我只是轉儲格式進我試圖轉換成一個字典的列表。

但是,這種方法只會接受一個值的關鍵。我想要的東西,有兩件事情就像

獅子吃斑馬 獅子吃狗

有一本字典是

獅:[「斑馬」,「狗」]

我不能想到這樣做的一種方式。任何幫助,將不勝感激。

回答

2

有兩種合理的方法可以使字典包含您添加的列表,而不是單個項目。首先是在添加新的值之前檢查現有的值。第二種是使用更復雜的數據結構,它在需要時負責創建列表。

這裏的第一種方法的一個簡單的例子:

predpreydic = {} 

with open(sys.argv[1]) as f: 
    for line in f: 
     pred, eats, prey = line.split() # splits on whitespace, so three values 
     if pred in predpreydic: 
      predpreydic[pred].append(prey) 
     else: 
      predpreydic[pred] = [prey] 

在第一種方法的變化與字典稍微更微妙的方法調用替換if/else塊:

 predpreydic.setdefault(pred, []).append(prey) 

setdefault方法將predpredic[pred]設置爲空列表(如果它尚不存在),然後返回該值(新的空列表或先前的現有列表)。它與另一種解決問題的方法非常相似,這是接下來的問題。

我提到的第二種方法涉及collections模塊(Python標準庫的一部分)中的the defaultdict class。這是一個字典,可在您請求尚不存在的密鑰時創建新的默認值。要按需創建值,它使用您在第一次創建defaultdict時提供的工廠函數。

這是你的計劃是什麼樣子使用它:

from collections import defaultdict 

predpreydic = defaultdict(list) # the "list" constructor is our factory function 

with open(sys.argv[1]) as f: 
    for line in f: 
     pred, eats, prey = line.split() 
     predpreydic[pred].append(prey) #lists are created automatically as needed 
+0

哦,感謝上帝,我以爲我會發瘋。我使用了第一種方法,因爲這是一項大學任務,我不完全確定我是否可以依賴導入defaultdict。儘管我找到了我想要的東西,但很多謝謝。 – user1877961

+0

+1。 @ user1877961歡迎來到SO!當像這樣的答案解決您的問題時,您可以單擊分數下方的空白複選標記以接受它。 – RocketDonkey

相關問題