【问题标题】:Searching Python Dictionary by key value is returning multiple, consecutive results, not just 1按键值搜索 Python 字典会返回多个连续的结果,而不仅仅是 1
【发布时间】:2013-10-28 22:54:21
【问题描述】:

我对 Python 比较陌生,但遇到以下问题。 我正在尝试编写一个程序来读取个人信息的 CSV 文件,然后根据输入的 ID 号显示个人信息。

除了我想要的结果之外,它几乎可以完美地工作,除了当我按 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)

任何帮助将不胜感激!

【问题讨论】:

    标签: python loops csv dictionary


    【解决方案1】:

    您需要为您处理的每一行重新初始化结果字段。

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

    【讨论】:

    • 布莱斯,谢谢!愚蠢的疏忽!我一定已经多次查看我的代码的那部分,实际上是在自言自语 - 解释“口头伪代码”中发生的事情,并且完全忽略了我初始化结果变量的位置。 (以及我如何不重新初始化它)。谢谢你的新鲜眼睛。我也很欣赏最后对代码的清理。 J
    猜你喜欢
    • 1970-01-01
    • 2015-05-16
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2011-03-21
    • 2020-02-10
    • 2012-07-08
    相关资源
    最近更新 更多