HackerRank Day 8 Solution in Python: Dictionaries and Maps

Today we will see the HackerRank Day 8 Solution in Python. The problem is named Dictionaries and Maps which is part of 30 Days of code on HackerRank. Let’s get started!

Day 8: Dictionaries and Maps Problem statement

We are given names and phone numbers, our task is to assemble a phone book that maps friends’ names to their respective phone numbers. When an unknown number of names are given, we have to print the associated entry from your phone book on a new line in the form name=phoneNumber. If an entry for the name is not found, we have to print Not found.

Sample Input

3
sam 99912222
tom 11122222
harry 12299933
sam
edward
harry

Sample Output

sam=99912222
Not found
harry=12299933

Explanation:
Sam is one of the keys in our dictionary, so we print sam=99912222.
Edward is not one of the keys in our dictionary, so we print Not found.
Harry is one of the keys in our dictionary, so we print harry=12299933.

You can solve the problem here.

HackerRank Day 8 Solution in Python

n = int(input())
name_numbers = [input().split() for i in range(n)]
phone_book={}

#Store the input as key and value pairs
for k,v in name_numbers:
    phone_book[k]=v

while True:
    #Check if the input name is present
    try:
        name = input()
        #If input name is present
        if name in phone_book:
            print('{}={}'.format(name, phone_book[name]))
        #If input name is not present
        else:
            print('Not found')
    except:
        break

Code Explanation

  • First, get the input from the user and store the input names and phone numbers as key and value pairs
  • Inside the try block, check if the input name is present in the dictionary
  • If the input name is present then print the name and the corresponding value(phone number)
  • If the input name is not present then print Not found

Also Read:

Share:

Author: Ayush Purawr