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.

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']}
"""

Edited 4 Years Ago by Lardmeister

This article has been dead for over six months. Start a new discussion instead.