简体   繁体   中英

Python 3 dictionary.get() function not working with sys.stdin

I am currently writing a dictionary program that allows the user to enter in two words: an English word and its foreign translation. Then, the user should be able to input a foreign word and retrieve the English word; however, I am required to use sys.stdin for the second half.

import sys

dictionary = dict()
userInput = input()
while userInput != "":
    buf = userInput.split()
    english = buf[0]
    foreign = buf[1]
    dictionary[foreign] = english
    userInput = input()

for userInput in sys.stdin:
    print(type(userInput))
    if userInput in dictionary:
        print(dictionary.get(userInput))
    else:
        print("Word not in dictionary.")

When I use sys.stdin, the dictionary.get() function is not functioning properly. When I simply use the normal input() function instead of sys.stdin, the dictionary is able to function properly. Why is this and how can I get sys.stdin to properly work with the dictionary search?

This code seems to work, but once again... it used input() instead of sys.stdin:

import sys

dictionary = dict()
userInput = input()
while userInput != "":
    buf = userInput.split()

    english = buf[0]
    foreign = buf[1]

    dictionary[foreign] = english
    userInput = input()

userInput = input()
while userInput != "":
    if userInput in dictionary:
        print(dictionary.get(userInput))
    else:
        print("Word not in dictionary")

    userInput = input()

Thanks!

A trailing '\\n' was the issue. string = string.rstrip('\\n') fixed this for me.

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