w3resource

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:

from collections import defaultdict
classes = (
    ('V', 1),
    ('VI', 1),
    ('V', 2),
    ('VI', 2),
    ('VI', 3),
    ('VII', 1),
)

class_rollno = defaultdict(list)

for class_name, roll_id in classes:
    class_rollno[class_name].append(roll_id)

print(class_rollno)

Sample Output:

defaultdict(<class 'list'>, {'V': [1, 2], 'VI': [1, 2, 3], 'VII': [1]})

Flowchart:

Python Collections: Find the class wise roll number from a tuple-of-tuples.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

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.



Python: Tips of the Day

Use Reversed() In for Loops:

>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking']
>>> for task in reversed(tasks):
...     print(task)
... 
cooking
gardening
picking up kids
laundry