Python Practical Assignment 8.1

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

  1. Start the program.
  2. Create a dictionary with some initial values.
  3. Insert a new key-value pair into the dictionary.
  4. Delete an existing key from the dictionary.
  5. Print the updated dictionary.
  6. 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.


Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top