Python Dictionaries and Maps | David Capella
View on GitHub

# Python Dictionaries and Maps

## Problem

Given N names and phone numbers, assemble a phone book that maps friendsâ€™ names to their respective phone numbers. You will then be given an unknown number of names to query your phone book for. For each name queried, print the associated entry from your phone book on a new line in the form name=phoneNumber; if an entry for name is not found, print Not found instead.

## Template

``````"""Loads a dictionary and then looks for people based on STDIN"""
import fileinput

pass

items = fileinput.input()

``````

## Pseudo Code

``````# Declare empty dict
# Declare threshold (to know when to start searching instead of adding)
# loop through items (do not have to skip first because it was already read when declaring threshold)
# if i less than threshold
# unpack item split into name, num
# load into dict, strip num (strip because it might have a \n)
# else (once we pass threshold)
# declare name from item
# get number from dict, else 0
# print name=num if name exists (not 0) else print not found
``````

## Code

#### Loop Through Items

``````address_book = {}
threshold = int(items[0])
for i, item in enumerate(items):
``````

#### Load Into Dict, Strip Num

``````if i < threshold:
name, num = item.split(' ')
``````

#### Get Number from Dict, Else 0

``````else:
name = item.strip()
num = address_book.get(name, 0)
``````

## Full Solution

``````"""Loads a dictionary and then looks for people based on STDIN"""
import fileinput

"""Fills an address book and looks for requested people.

Parameters
----------
items: fileinput obj
Can also be a list.
First element is an int telling how many people to load into dict.
Each person must be one string with a single name, space, phone number.

Returns
-------
None: None
Prints person's name and phone number else not found.

"""
threshold = int(items[0])
for i, item in enumerate(items):
if i < threshold:
name, num = item.split(' ')
else:
name = item.strip()
num = address_book.get(name, 0)