Raindeerstream
Raindeerstream

Reputation: 33

Python Phonebook

I Have searched for similar tasks but i have not found anyting comprehensive. I have been given a task to make a phonebook with the following requirements.

  1. -add name number - adds a name and a number

    -lookup name – prints the number for name

    -alias name newname – adds a "nickname" to an already existing name

    -change name number – changes the number to an alredy existing name

    -save filename – Saves the phonebook to a file

    -load filename –Reads the file and throws away the phonebook in the memory(wat?) After this only the phonebook from the file should exist.

This is my code so far:

prompt = ('command (add/lookup/alias/change/save/load/quit/)')

phonebook = {}

run = True

while run:

command = raw_input(prompt)
if command == 'quit':
    run = False

elif command == 'add':
    name = raw_input('name?')
    number = raw_input ('number?')
    phonebook[name]=number

elif command == ('lookup'):
    name=raw_input ("Name?:")
    if name in phonebook:
        print name, phonebook[name]
    else:
        print "Does not exist"

So i need help on how to implement the alias and change commandos. The save and load i think i can figure out myself but any help on those will be appriciated aswell.

Thanks

Upvotes: 1

Views: 3716

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117856

You could reformat your phonebook to a nested dictionary

phonebook = {
  "Steven": {"Alias": "Steve", "Number": "123-456-7890"}, 
  "Michael": {"Alias": "Mike", "Number": "987-654-3210"}
}

Then you could look things up like

>>> phonebook['Steven']['Number']
'123-456-7890'

Then your last two functions could be

elif command == ('alias'):
    name = raw_input ("Name?:")
    nickname = raw_input ("Alias?:")
    if name in phonebook:
        phonebook[name]['Alias'] = nickname
    else:
        print "Does not exist"

elif command == ('change number'):
    name = raw_input ("Name?:")
    number = raw_input ("Number?:")
    if name in phonebook:
        phonebook[name]['Number'] = number
    else:
        print "Does not exist"

Edit

elif command == 'add':
    name = raw_input('name?')
    number = raw_input ('number?')
    phonebook[name] = {'Alias': '', 'Number': number}

elif command == ('lookup'):
    name = raw_input ("Name?:")
    if name in phonebook:
        print name, phonebook[name]
    else:
        print "Does not exist"

Upvotes: 3

Related Questions