Q.Write a program to input your friend’s, names and their phone numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →A phone book is the textbook use of a dictionary: name → number. Build it from user input,
then each sub-task is one dictionary tool: loop over items() to display, index-assignment to
add and modify, del/pop to delete, in to check membership, and sorted(d) to show it in
name order.
Build the dictionary
# Friends' phone book
phonebook = {}
n = int(input("How many friends? "))
for i in range(n):
name = input("Name : ")
phone = input("Phone : ")
phonebook[name] = phone # name is the key, number the value
Sample data used below:
phonebook = {'Riya': '9811111111', 'Aman': '9822222222', 'Zoya': '9833333333'}
a) Display the name and phone number of all friends
for name, phone in phonebook.items():
print(name, ":", phone)
Riya : 9811111111
Aman : 9822222222
Zoya : 9833333333
b) Add a new key-value pair and display the modified dictionary
Assigning to a key that does not exist creates a new pair.
phonebook['Kabir'] = '9844444444'
print(phonebook)
{'Riya': '9811111111', 'Aman': '9822222222', 'Zoya': '9833333333', 'Kabir': '9844444444'}
c) Delete a particular friend
name = input("Friend to delete: ") # e.g. Aman
if name in phonebook:
del phonebook[name]
print(phonebook)
else:
print(name, "not found")
{'Riya': '9811111111', 'Zoya': '9833333333', 'Kabir': '9844444444'}
d) Modify the phone number of an existing friend
Assigning to a key that already exists overwrites its value — same syntax as (b), opposite effect.
name = input("Friend to modify: ") # e.g. Zoya
if name in phonebook:
phonebook[name] = input("New phone: ") # e.g. 9855555555
print(phonebook)
{'Riya': '9811111111', 'Zoya': '9855555555', 'Kabir': '9844444444'}
e) Check whether a friend is present
name = input("Friend to search: ") # e.g. Riya
if name in phonebook:
print(name, "is present")
else:
print(name, "is not present")
Riya is present
``` …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.