2016-04-21 1308 views
-1

問題 我試圖將用戶輸入指定爲字典中的鍵。如果用戶輸入是一個鍵然後打印出它的值,否則打印無效的鍵。問題在於鍵和值將來自文本文件。爲了簡單起見,我將使用隨機數據作爲文本。任何幫助,將不勝感激。Python:將用戶輸入指定爲字典中的鍵

file.txt的

狗,樹皮
貓,喵
小鳥,唧唧

代碼

def main(): 
    file = open("file.txt") 
    for i in file: 
     i = i.strip() 
     animal, sound = i.split(",") 
     dict = {animal : sound} 

    keyinput = input("Enter animal to know what it sounds like: ") 
    if keyinput in dict: 
     print("The ",keyinput,sound,"s") 
    else: 
     print("The animal is not in the list") 
+0

你的問題是?你應該閱讀[mcve]。 –

回答

6

在循環的每次迭代,你是重新定義字典,而是添加新條目:

d = {} 
for i in file: 
    i = i.strip() 
    animal, sound = i.split(",") 
    d[animal] = sound 

然後,您可以通過鍵來訪問字典項:

keyinput = input("Enter animal to know what it sounds like: ") 
if keyinput in d: 
    print("The {key} {value}s".format(key=keyinput, value=d[keyinput])) 
else: 
    print("The animal is not in the list") 

請注意,我也改變了字典變量名從dictd,因爲dict是一個很差的變量名稱選擇,因爲它是隱藏內置的dict

此外,我改進了構造報告字符串的方式,並改爲使用string formatting。如果您輸入Dog,則輸出爲The Dog barks


您也可以初始化字典在一行中使用dict()構造:

d = dict(line.strip().split(",") for line in file) 

作爲一個側面說明,to follow the best practices and keep your code portable and reliable,使用with context manager打開文件時 - 這將需要關心其關閉正確:

with open("file.txt") as f: 
    # ... 
2

OP,我已經在代碼中寫了一些詳細的解釋性註釋並修復了一些問題;我可能忽略了一些東西,但檢查出來。

  • 其一,避免使用dict作爲變量名,因爲它陰影Python的bult-在dict方法。
  • 請記住,在大多數情況下,您需要在循環前聲明變量以使其可訪問之後的循環;這適用於你的字典。
  • 還有,記得閱讀後要關閉文件/寫,除非你使用with open(filename) ...

    def main(): 
        # declare a new, empty dictionary to hold your animal species and sounds. 
        # Note that I'm avoiding the use of "dict" as a variable name since it 
        # shadows/overrides the built-in method 
        animal_dict = {} 
        file = open("file.txt") 
        for i in file: 
         i = i.strip() 
         animal, sound = i.split(",") 
         animal_dict[animal] = sound 
    
        # Remember to close your files after reading 
        file.close() 
    
        keyinput = input("Enter animal to know what it sounds like: ") 
        if keyinput in animal_dict: 
    
         # here, keyinput is the string/key and to do a lookup 
         # in the dictionary, you use brackets. 
         # animal_dict[keyinput] thus returns the sound 
    
         print("The ",keyinput,animal_dict[keyinput],"s") 
        else: 
         print("The animal is not in the list") 
    
+0

沒有解釋的轉儲代碼對OP或未來的讀者沒有幫助。 –

+0

@MorganThrapp對此進行操作...... :) – jDo

1

有在每一行,我改變什麼解釋什麼是我改的意見,而是幫助可讀性,我把他們也放在這裏。

  • 在線2我實例化的字典 - 你以前 重新定義字典的每一行
  • 在第7行,我改變你的 代碼的東西添加到字典中,而不是隻建立一個 新一。這是適當的字典語法。
  • 在第10行,我改變「如果 keyinput在字典」到「如果keyinput在dict.keys()」,因爲你 檢查,看是否存在的動物,並在文件 動物成爲字典的鍵。

    def main(): 
    
        dict = {} #Create an empty dictionary to add to 
        file = open("file.txt") 
        for i in file: 
         i = i.strip() 
         animal, sound = i.split(",") 
         dict[animal] = sound #This is how you add a key/value pair to a dictionary in Python 
    
        keyinput = input("Enter animal to know what it sounds like: ") 
        if keyinput in dict.keys(): #Add .keys() to iterate through dictionary keys 
         print("The ",keyinput,sound,"s") 
        else: 
         print("The animal is not in the list") 
    
+1

@MorganThrapp對每一行我都有評論,你有看到那些嗎?這不僅僅是一個代碼轉儲。 –

+0

@MorganThrapp我不認爲伊恩只是傾銷代碼,請刪除您的downvote – haifzhan

1

首先你不應該命名變量相同的關鍵字。其次,將輸入放入字典的方式將覆蓋以前的值。您需要創建字典,然後添加新值。 第三,你的輸出值sound不從字典

dict作爲一個變量應命名爲mydict

初始循環

之前創建mydict = {}得到它在第一循環設置mydict[animal] = sound

mydict['dog'] = 'bark' # This is what happens 

print如果它在列表中,則爲10和mydict[keyinput]

您也可以使用mysound = mydict.get(keyinput, "not in dictionary")代替if。

Why dict.get(key) instead of dict[key]?