-2

Problem I was trying to assign user input as a key in a dictionary. If user input is a key then print out its value, else print invalid key. The problem is the keys and the values will be from a text file. For simplicity I will just use random data for the text. Any help would be appreciated.

file.txt

Dog,bark
Cat,meow
bird,chirp

Code

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")
Kitty
  • 125
  • 1
  • 2
  • 8

4 Answers4

6

On every iteration of the loop, you are redefining the dictionary, instead, add new entries:

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

Then, you can access the dictionary items by key:

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")

Note that I've also changed the dictionary variable name from dict to d, since dict is a poor variable name choice because it is shadowing the built-in dict.

Also, I've improved the way you construct the reporting string and used a string formatting instead. If you would enter Dog, the output would be The Dog barks.


You can also initialize the dictionary in one line using the dict() constructor:

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

As a side note, to follow the best practices and keep your code portable and reliable, use the with context manager when opening the file - it would take care about closing it properly:

with open("file.txt") as f:
    # ...
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
2

OP, I've written some verbose explanatory notes in the code and fixed a few issues; I might have overlooked something but check it out.

  • For one, avoid using dict as a variable name since it shadows Python's bult-in dict method.
  • Remember that , in most cases, you need to declare variables before a loop to make them accessible after the loop; this applies to your dictionary.
  • Also, remember to close files after reading/writing unless you use 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")
    
jDo
  • 3,962
  • 1
  • 11
  • 30
1

There were comments on every line I changed something explaining what I changed, but to help readability, I'm putting them here too.

  • On Line 2 I instantiated a dictionary - you were previously re-defining a dictionary for each line
  • On Line 7 I changed your code to add something to the dictionary instead of just creating a new one. That's proper dictionary syntax.
  • On Line 10 I changed "if keyinput in dict" to "if keyinput in dict.keys()", since you're checking to see if the animal exists, and the animals in your file become the keys of the dictionary.

    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 There are comments on every line I changed, did you see those? It wasn't just a code dump. –  Apr 21 '16 at 20:46
  • @MorganThrapp I dont think Ian was just dumping code, please remove your downvote – Haifeng Zhang Apr 21 '16 at 20:49
1

First of all you should not name a variable the same as a keyword. Secondly, the way you put the input into the dictionary will overwrite the previous values. You need to create the dictionary and then add the new values. Third, you output the value sound without getting it from the dictionary

dict as a variable should be named mydict

create mydict = {} before the initial loop

set mydict[animal] = sound in the first loop

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

print keyinput and mydict[keyinput] if it is in the list.

You can also use mysound = mydict.get(keyinput, "not in dictionary") instead of the if.

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

Community
  • 1
  • 1
sabbahillel
  • 4,357
  • 1
  • 19
  • 36