A dictionary containing phone numbers as  keys and names as values is named mydict.  Write a python program to delete the key value  pair from this dictionary after accepting phone  number from the user. 

 

Answer:

# Assume that mydict is a dictionary containing phone numbers as keys and names as values

# For example, mydict = {'1234567890': 'Alice', '0987654321': 'Bob', '1357924680': 'Charlie'}

# Ask the user to enter a phone number

phone = input("Please enter a phone number: ")

# Check if the phone number is in mydict

if phone in mydict:

    # Delete the key-value pair using del or pop

    del mydict[phone]

    # Print a confirmation message

    print(f"The phone number {phone} has been deleted from mydict.")

else:

    # Print an error message

    print(f"The phone number {phone} is not in mydict.")

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.