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.

Dani AI

Generated

A short, reliable plan: open the file, read it line by line, skip blank lines, split each line on whitespace, treat the first token as the name and the remaining tokens as that person's phone numbers, and accumulate numbers for names that appear more than once. The function should return the dictionary (do not print inside the function). , that minimal strategy will get you started; is right that posting your attempt helps, and 's reply already shows splitting is the right idea — the version below is more general and avoids the "only two numbers" assumption.

from collections import defaultdict

def getPhoneBook(filename):
    """Return {name: [phone,...]} for a file where each line is:
       name [phone1 phone2 ...]"""
    phonebook = defaultdict(list)
    with open(filename, 'r', encoding='utf-8') as fh:
        for raw in fh:
            line = raw.strip()
            if not line:
                continue
            parts = line.split()
            name, *phones = parts
            phonebook[name].extend(phones)
    return dict(phonebook)

Notes and quick troubleshooting:

  • This handles any number of phones per line and will merge phones if the same name appears multiple times.
  • If you want to avoid duplicate numbers, replace the list with an ordered set-like approach (preserve order with a small helper).
  • If phone tokens can contain spaces or the name can contain spaces, use line.split(maxsplit=1) or a regex to separate name from the rest.
  • Add simple validation with a regex if you need to enforce formats, but keep parsing and validation separate for clarity.

If you post your current code, it will be easier to point out the exact problem. This snippet is a clean, testable starting point you can adapt for validation, de-duplication, or alternative input formats.

Recommended Answers

All 3 Replies

You forgot your code and description of your problem.

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, networking, learning, and sharing knowledge.