Python: Assigning user input as key in dictionary -


problem trying assign user input key in dictionary. if user input key print out value, else print invalid key. problem keys , values text file. simplicity use random data text. appreciated.

file.txt

dog,bark
cat,meow
bird,chirp

code

def main():     file = open("file.txt")     in file:         = i.strip()         animal, sound = i.split(",")         dict = {animal : sound}      keyinput = input("enter animal know sounds like: ")     if keyinput in dict:         print("the ",keyinput,sound,"s")     else:         print("the animal not in list") 

on every iteration of loop, redefining dictionary, instead, add new entries:

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

then, can access dictionary items key:

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

note i've changed dictionary variable name dict d, since dict poor variable name choice because shadowing built-in dict.

also, i've improved way construct reporting string , used string formatting instead. if enter dog, output the dog barks.


you can initialize dictionary in 1 line using dict() constructor:

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

as side note, to follow best practices , keep code portable , reliable, use with context manager when opening file - take care closing properly:

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

Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -