Reputation: 109
The main aim of the code is to take n lines of input and add this data to dictionary and then perform n queries on dictionary. however only the last query is working correctly.
from sys import stdin
n = int(input())
mydict={}
for i in range(0,n):
pairs=input().split(' ')
key=pairs[0]
value=pairs[1]
mydict[key]=value
print (mydict)
for a in stdin:
print(a)
if(a in mydict):
print(a+'='+mydict[a])
else:
print("Not Found")
Upvotes: 0
Views: 48
Reputation: 87074
The input obtained from stdin
includes the new line character(s), however, due to the use of input()
the keys in the dictionary do not, hence the lookup fails. It works on the final iteration because the line is terminated by end of file rather than new line.
You could fix it by stripping whitespace at the end of the line in the second loop:
for a in stdin:
a = a.rstrip()
print(a)
if a in mydict:
print(a+'='+mydict[a])
else:
print("Not Found")
Upvotes: 2
Reputation: 1410
The content read from stdin is original stream.
So when you hit the enter key, the '\n'
is add to the stream.
Solution 1: use input method.
Solution 2: read from stdin, and use rstrip()
method before query from the dict.
Upvotes: 0