Python: Find the class wise roll number from a tuple-of-tuples
Python Collections: Exercise-32 with Solution
Write a Python program to find the class wise roll number from a tuple-of-tuples.
Sample Solution:
Python Code:
# Import the defaultdict class from the collections module
from collections import defaultdict
# Create a tuple 'classes' containing class names and roll numbers
classes = (
('V', 1),
('VI', 1),
('V', 2),
('VI', 2),
('VI', 3),
('VII', 1),
)
# Create a defaultdict 'class_rollno' to store lists of roll numbers for each class
class_rollno = defaultdict(list)
# Loop through the tuples in 'classes'
for class_name, roll_id in classes:
# Append the roll number 'roll_id' to the list associated with class 'class_name' in 'class_rollno'
class_rollno[class_name].append(roll_id)
# Print the resulting dictionary 'class_rollno'
print(class_rollno)
Sample Output:
defaultdict(<class 'list'>, {'V': [1, 2], 'VI': [1, 2, 3], 'VII': [1]})
Flowchart:
Python Code Editor:
Previous: Write a Python program to count the most common words in a dictionary.
Next: Write a Python program to count the number of students of individual class.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/collections/python-collections-exercise-32.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics