I need to create a phone directory with given inputs, then I need to query the dictionary for unknown number of given keys, if not found, print Not found. Link of Original HackerRank Problem here
I have written this code in Python3, and it's working fine. Please review, and suggest other ways of taking unknown number of inputs. Should it be done without using sys
?
import sys
phone={}
n = int(input())
for _ in range(n):
line = input().split()
phone[line[0]] = line[1]
for line in sys.stdin:
key=line.strip('\n')
try:
print(key+'='+phone[key])
except KeyError:
print('Not found')
1 Answer 1
Take care to adhere to PEP 8 code formatting guidelines. In particular, there should be a space before and after each =
and +
. The KeyError
handler should have just one level of indentation.
The phonebook could be constructed using a one-liner. I consider it good practice to specify maxsplit=1
, though it makes no practical difference when you are assured that the input will be well formed.
Getting the rest of the input using for line in sys.stdin
is not a bad approach, I think.
import sys
n = int(input())
phonebook = dict(input().split(maxsplit=1) for _ in range(n))
for line in sys.stdin:
key = line.strip('\n')
try:
print('{0}={1}'.format(key, phonebook[key]))
except KeyError:
print('Not found')
Explore related questions
See similar questions with these tags.