HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Querying a phone directory until end of input is reached

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
directoryuntilqueryinginputreachedphoneend

Problem

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

Solution

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

Code Snippets

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

Context

StackExchange Code Review Q#149269, answer score: 2

Revisions (0)

No revisions yet.