Page 280 - CTS - CSA TP - Volume 2
P. 280
COMPUTER SOFTWARE APPLICATION - CITS
TASK 3 : Nested Dictionary
# Creating a nested dictionary
library = {
‘fiction’: {‘novels’: 50, ‘short stories’: 30},
‘non-fiction’: {‘history’: 20, ‘science’: 40}
}
# Accessing nested dictionary elements
print(“Library Book Information”)
print(“-------------------------”)
print(“Number of novels:”, library[‘fiction’][‘novels’])
print(“Number of science books:”, library[‘non-fiction’][‘science’])
Explanation:
• The dictionary ‘library’ is nested with categories (‘fiction’, ‘non-fiction’) containing subcategories and their
counts.
• Nested elements are accessed using multiple keys.
Output:
TASK 4: Dictionary Methods
student = {
‘name’: ‘SreeHari’,
‘age’: 20,
‘grade’: ‘A’
}
# Using dictionary methods
keys = student.keys()
values = student.values()
items = student.items()
print(“Keys:”, keys)
print(“Values:”, values)
print(“Items:”, items)
Explanation:
• The methods keys(), values(), and items() are used to retrieve keys, values, and key-value pairs, respectively.
Output:
265
CITS : IT & ITES - Computer Software Application - Exercise 128