Problem 1: Phone book.
A phone book file is organized so that each line is an entry for one person. Each line has the
following format: first, a name (one word, no spaces), then zero or more phone numbers, each
preceded by a space (no spaces within a phone number).
For example, these lines might be entries in a phone book file:
Karen 555-231-5437 898-340-9870
Ala 212-889-0314

Write a function named getPhoneBook() that takes one parameter - the name of a file.
getPhoneBook() should read the contents of the named file into a dictionary in which each
name is a key and each value is a list of associated phone numbers.
getPhoneBook should return (not print out!) the dictionary it constructs.

## All 3 Replies

I have no idea where to start

Karen 555-231-5437 898-340-9870
Ala 212-889-0314

Maybe this will help a little:

``````# raw data of name and phone number(s) with space separator
data = """\
Karen 555-231-5437 898-340-9870
Alma 212-889-0314
Frank 555-245-5348 898-340-7890"""

fname = "phonebook.txt"
# write the raw data to a text file
with open(fname, "w") as fout:
fout.write(data)

# read the data back in from file and convert to a
# name:[phonenumbers] dictionary pair
d = {}
for line in open(fname, "r"):
# remove trailing whitespace
line = line.rstrip()
# convert to a list
line = line.split()
d.setdefault(line[0], []).append(line[1])
# take care of person with 2 phone numbers
if len(line) > 2:
d.setdefault(line[0], []).append(line[2])

import pprint
pprint.pprint(d)

"""my output >>>
{'Alma': ['212-889-0314'],
'Frank': ['555-245-5348', '898-340-7890'],
'Karen': ['555-231-5437', '898-340-9870']}
"""
``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.