简体   繁体   中英

Searching Python Dictionary by key value is returning multiple, consecutive results, not just 1

I am relatively new to Python and I am having trouble with the following. I am trying to write a program that would read a CSV file of personal information and then display an individuals information based on entering an ID number.

It is almost working perfectly, except that when I search by id number, it is returning all of the results (rows) preceding the desired result, in addition to the result I want.

I am reading a CSV file into a dictionary. I am then naming the fields dynamically from the file based on the names from the CSV (theoretically the CSV file can contain 2 columns of data or 100, as long as there is one field named "id").

csvfile.txt looks like:

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

What I want is when I search for id "1", it returns:

"
id: 1
name: Jay
age: 35
"

...and it does.... but if I search for id "3", I am getting:

"
id: 1
name: Jay
age: 35

id: 2
name: Jen
age: 36

id: 3
name: Sam
age: 38
"

I can't figure out why it is not just returning the one row I am asking for... here is the core of the code:

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)

Any help would be greatly appreciated!

You need to re-initialize resultfields for each row you process.

#!/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)

Output now looks like:

name: mike
age: 26

done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM