Python Program to Make a Simple Phone Book
Beginner · Dictionaries
A phone book stores names with their phone numbers, which is a natural fit for a dictionary: the name is the key and the number is the value. This program adds, searches, updates and deletes contacts, with the menu choices written out in a list so it runs without any typing.
Program
Added Meera Found Arjun : 91234 56789 Updated Riya to 90000 11111 Deleted Arjun Arjun is not in the phone book Phone book now: Meera - 99887 76655 Riya - 90000 11111
How it works
- The dictionary
phone_bookmaps each name (the key) to a phone number (the value), stored as a string so that spaces and leading zeros are kept. - The list
actionsstands in for a user picking options from a menu, and the comment shows theinput()version. - Adding and updating both use
phone_book[name] = number, but the update branch first checks that the name exists. delremoves a contact, and searching is a plain lookup onceinhas confirmed the name is there.- A request for a name that is not in the book falls through to the last
else, which is why the second search for Arjun says he is gone.
Other ways to write it
Search by part of a name
Riya Sharma - 98765 43210 Ria Thomas - 99887 76655
Real phone books let you type part of a name. Lower-casing both sides makes the search ignore case, and the comprehension keeps every contact whose name contains the query.
Saving the phone book to a file
Loaded from file: {'Riya': '98765 43210', 'Arjun': '91234 56789', 'Meera': '99887 76655'}A dictionary disappears when the program ends. json.dump() writes it to a file and json.load() reads it back as a dictionary, so the contacts survive between runs.
Try it yourself
Add ("search", "Kabir", None) to the list of actions and check the message it prints.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Check if a Key Exists in a Dictionary
- Remove a Key from a Dictionary
- a Menu-Driven List
- Read and Write a JSON File
- Find Students Who Scored Above 75 Using a Dictionary
- Merge Two Dictionaries
- Sort a Dictionary by Value
- Sort a Dictionary by Key
- Create a Dictionary from Two Lists
- Find the Sum of All Values in a Dictionary
All Python programs · CBSE class 12 practical file · Python exercises