3
\$\begingroup\$

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')
200_success
146k22 gold badges190 silver badges479 bronze badges
asked Dec 8, 2016 at 6:19
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

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')
answered Dec 8, 2016 at 7:10
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.