2013-10-28 39 views
0

我對Python相對來說比較陌生,我遇到了以下問題。 我正在嘗試編寫一個程序,用於讀取個人信息的CSV文件,然後根據輸入的ID號顯示個人信息。按鍵值搜索Python字典返回多個連續的結果,而不僅僅是1

除了當我用id號搜索時,除了我想要的結果之外,它還返回所需結果之前的所有結果(行),它幾乎可以完美工作。

我正在將CSV文件讀取到字典中。然後,我根據CSV中的名稱從文件中動態地命名字段(理論上CSV文件可以包含2列數據或100,只要有一個名爲「id」的字段)。

csvfile.txt樣子:

id,name,age 
1,jay,35 
2,jen,36 
3,sam,38 
4,mike,26 

我想,當我搜索ID爲 「1」,則返回:

" 
id: 1 
name: Jay 
age: 35 
" 

...它確實....但是如果我搜索ID爲「3」,我得到:

" 
id: 1 
name: Jay 
age: 35 

id: 2 
name: Jen 
age: 36 

id: 3 
name: Sam 
age: 38 
" 

我想不通爲什麼它不只是返回一個排我要求......這裏是核心代碼:

def runprogram(): 
import csv 
file = open(csvfile.txt, "r") #open my test file 
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')  

totalfields = (len(reader.fieldnames)) #count all the fields in the files for the purpose of for looping. 

result={} #new dictionary named result 

resultfields = "" 

i=1 
for row in reader: 
    for i in range(1,totalfields): 
     resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n" 
     i+1 
    result[row['id']] = resultfields #storing each line from the CSV into the results dictionary under the key "id" 

#this was just some code so I could exit my program by typing "exit" in the input box... 
idvalue="" 

while idvalue != "exit": 
    #display the box in which to enter a id number 

    if idvalue =="":  
     message = "Enter id Number" 
    else: 
     message = result[idvalue] 

    #using easyGUI for my input and display boxes.  
    idvalue = eg.enterbox(msg=message,title='Print Results', default='', strip=True) 

    if idvalue: 
     identered = "1"#this was used for testing.   
     printresults(results[idvalue]) #call printresults function 
    else: 
     programmenu() 

    if idvalue =="exit": 
     exit() 

def printresults(results): 
     output = "Information Requested:\n" + results 

     print(output) 

任何幫助將不勝感激!

回答

2

您需要重新初始化您處理的每一行的結果字段。現在

#!/usr/bin/python 
import csv 
def printresults(results): 
    print ("Information Requested:\n" + results) 

file = open("/tmp/csvfile.txt", "r") 
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',') 

totalfields = (len(reader.fieldnames)) 
result={} 

for row in reader: 
    resultfields = "" 
    for i in range(1,totalfields): 
     resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n" 
    result[row['id']] = resultfields 

idvalues = ["exit", "4"] 
while 1: 
    idvalue = idvalues.pop() #eg.enterbox(msg=message,title='Print Results', default='', strip=True)        

    if idvalue == "": 
     message = "Enter id Number" 

    elif idvalue =="exit": 
     print "done" 
     exit() 

    else: 
     message = result[idvalue] 
     print(message) 

輸出的樣子:

name: mike 
age: 26 

done 
+0

布萊斯,謝謝!愚蠢的疏忽!我必須多次查看我的代碼段,從字面上與自己交談 - 解釋「口頭僞代碼」中發生的事情,並完全忽略了我初始化結果變量的位置。 (以及我如何不重新初始化它)。謝謝你的新眼睛。我很欣賞代碼在那裏的清理。 Ĵ – Jay

相關問題