Python Programs on Dictionaries
- Write a python program for demonstrating the
- creation of dictionary
- accessing dictionary elements
- modifying dictionary elements
- finding length and possible operations.
- Write a python program to create a dictionary of students with keys as roll numbers and values as names. Perform operations like insert, update and modify student data.
Logic:
- Initialize a dictionary using curly braces {} with key-value pairs. Keys can be strings, numbers, or tuples, values can be any type (strings, lists, dictionaries, etc.).
sample_dict = {"name": "ipl", "age": 18, "city": "Mumbai", "hobbies": ["cricket", "football"]} - Updating existing keys with new values (dict[key] = value).
- Use del to remove a specific key or pop(key, default) to remove and return a value.
Program:
# a) Program to demonstrate dictionary operations
# 1. Creating a dictionary
sample_dict = {"name": "Ram", "age": 25, "city": "New York", "hobbies": ["reading", "cycling"] }
print("Original dictionary:", sample_dict)
# 2. Accessing dictionary elements
print("\n Accessing elements:")
print("Name:", sample_dict["name"])
print("Hobbies:", sample_dict.get("hobbies"))
# 3. Modifying dictionary elements
print("\nModifying elements:")
sample_dict["age"] = 26 # Update existing key
sample_dict["city"] = "Boston" # Update existing key
print("After modifying age and city:", sample_dict)
# 4. Adding new key-value pairs
sample_dict["occupation"] = "Scientist" # Add new key-value pair
print("After adding occupation:", sample_dict)
# 5. Finding the length of the dictionary
print("\n Length of dictionary:", len(sample_dict))
# 6. Other possible operations
print("\n Other operations:")
# Removing a key-value pair
del sample_dict["hobbies"]
print("After removing hobbies:", sample_dict)
# Using pop() to remove and return a value
city = sample_dict.pop("city")
print("Popped city:", city)
print("After popping city:", sample_dict)
# Iterating over keys
print("Keys:")
for key in sample_dict:
print(key)
# Iterating over values
print("Values:")
for value in sample_dict.values():
print(value)
# Iterating over key-value pairs
print("Key-Value pairs:")
for key, value in sample_dict.items():
print(f"{key}: {value}")
# Clearing all items
sample_dict.clear()
print("After clearing dictionary:", sample_dict)
Output:
Original dictionary: {'name': 'Ram', 'age': 25, 'city': 'Hyderabad', 'hobbies': ['reading', 'cycling']}
Accessing elements:
Name: Ram
Hobbies: ['reading', 'cycling']
Modifying elements:
After modifying age and city: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'hobbies': ['reading', 'cycling']}
After adding occupation: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'hobbies': ['reading', 'cycling'], 'occupation': 'Scientist'}
Length of dictionary: 5
Other operations:
After removing hobbies: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'occupation': 'Scientist'}
Popped city: Mumbai
After popping city: {'name': 'Ram', 'age': 26, 'occupation': 'Scientist'}
Keys:
name
age
occupation
Values:
Ram
26
Scientist
Key-Value pairs:
name: Ram
age: 26
occupation: Scientist
After clearing dictionary: {}
Accessing elements:
Name: Ram
Hobbies: ['reading', 'cycling']
Modifying elements:
After modifying age and city: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'hobbies': ['reading', 'cycling']}
After adding occupation: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'hobbies': ['reading', 'cycling'], 'occupation': 'Scientist'}
Length of dictionary: 5
Other operations:
After removing hobbies: {'name': 'Ram', 'age': 26, 'city': 'Mumbai', 'occupation': 'Scientist'}
Popped city: Mumbai
After popping city: {'name': 'Ram', 'age': 26, 'occupation': 'Scientist'}
Keys:
name
age
occupation
Values:
Ram
26
Scientist
Key-Value pairs:
name: Ram
age: 26
occupation: Scientist
After clearing dictionary: {}
####### b) Student Dictionary with Interactive Operations ########
# Initialize student dictionary
students = {101: "kgps", 102: "kbk", 103: "grs"}
print("Initial student dictionary: {}".format(students))
while True:
print("\n Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit")
choice = input("Enter your choice (1-5): ").strip()
if choice == "1": # Insert new student
roll_no_input = input("Enter roll number: ").strip()
roll_no = int(roll_no_input)
if roll_no in students:
print("Roll number %d already exists!" % roll_no)
else:
name = input("Enter student name: ").strip()
students[roll_no] = name
print("Student added: {}: {}".format(roll_no, name))
elif choice == "2": # Update existing student
roll_no_input = input("Enter roll number to update: ").strip()
roll_no = int(roll_no_input)
if roll_no in students:
name = input("Enter new name: ").strip()
students[roll_no] = name
print("Updated student: {}: {}".format(roll_no, name))
else:
print("Roll number %d not found!" % roll_no)
elif choice == "3": # Delete student
roll_no_input = input("Enter roll number to delete: ").strip()
roll_no = int(roll_no_input)
if roll_no in students:
name = students.pop(roll_no)
print("Deleted student: {}: {}".format(roll_no, name))
else:
print("Roll number %d not found!" % roll_no)
elif choice == "4": # Display all students
if students:
print("Student list:")
for roll_no, name in students.items():
print("Roll: %d, Name: %s" % (roll_no, name))
else:
print("No students in dictionary!")
elif choice == "5": # Exit
print("Exiting program...")
break
else:
print("Invalid choice! Please enter 1-5.")
Output:
Initial student dictionary: {101: 'kgps', 102: 'kbk', 103: 'grs'}
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 1
Enter roll number: 104
Enter student name: pmd
Student added: 104: pmd
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 2
Enter roll number to update: 101
Enter new name: mad
Updated student: 101: mad
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 4
Student list:
Roll: 101, Name: mad
Roll: 102, Name: kbk
Roll: 103, Name: grs
Roll: 104, Name: pmd
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 5
Exiting program...
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 1
Enter roll number: 104
Enter student name: pmd
Student added: 104: pmd
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 2
Enter roll number to update: 101
Enter new name: mad
Updated student: 101: mad
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 4
Student list:
Roll: 101, Name: mad
Roll: 102, Name: kbk
Roll: 103, Name: grs
Roll: 104, Name: pmd
Options: 1=Insert, 2=Update, 3=Delete, 4=Display, 5=Exit
Enter your choice (1-5): 5
Exiting program...