Write a Python Program to Insert and Delete from Dictionary
Introduction
A dictionary in Python is used to store data in key-value pairs. We can insert new items and delete existing items using simple methods.
Logic to Write the Code
- Start the program.
- Create a dictionary with some initial values.
- Insert a new key-value pair into the dictionary.
- Delete an existing key from the dictionary.
- Print the updated dictionary.
- End the program.
Source Code (Beginner Friendly)
# Python program to insert and delete from dictionary
# Creating a dictionary
student = {
"name": "Avi",
"roll_no": 101,
"course": "Python"
}
# Inserting a new key-value pair
student["grade"] = "A"
# Deleting a key-value pair
del student["course"]
# Printing the updated dictionary
print(student)
Sample Output
{'name': 'Avi', 'roll_no': 101, 'grade': 'A'}
Viva Questions with Answers
1. What is a dictionary in Python?
A dictionary is a collection of key-value pairs.
2. How do you insert a new item into a dictionary?
By assigning a value to a new key.
Example: dict_name["key"] = value
3. How do you delete an item from a dictionary?
By using the del keyword.
Example: del dict_name["key"]
4. Are dictionary keys unique?
Yes, keys in a dictionary must be unique.
5. What happens if we delete a key that does not exist?
It will give a KeyError.
