Tuples and Dictionaries
Jharkhand Board · Class 11 · Computer Science
NCERT Solutions for Tuples and Dictionaries — Jharkhand Board Class 11 Computer Science.
Interactive on Super Tutor
Studying Tuples and Dictionaries? Get the full interactive chapter.
Quizzes, flashcards, AI doubt-solver and a step-by-step study plan — built for ncert solutions and more.
1,000+ Class 11 students started this chapter today
Exercise
1Consider the following tuples, tuple1 and tuple2:
tuple1 = (23,1,45,67,45,9,55,45)
tuple2 = (100,200)
Find the output of the following statements:
i. print(tuple1.index(45))
ii. print(tuple1.count(45))
iii. print(tuple1 + tuple2)
iv. print(len(tuple2))
v. print(max(tuple1))
vi. print(min(tuple1))
vii. print(sum(tuple2))
viii. print(sorted(tuple1)) then print(tuple1)Show solution
i. print(tuple1.index(45))
The `index()` method returns the index of the first occurrence of the given element.
In tuple1, 45 first appears at index 2 (0-based indexing).
ii. print(tuple1.count(45))
The `count()` method returns the number of times the element appears in the tuple.
45 appears at indices 2, 4, and 7 — a total of 3 times.
iii. print(tuple1 + tuple2)
The `+` operator concatenates two tuples.
iv. print(len(tuple2))
The `len()` function returns the number of elements in the tuple.
tuple2 has 2 elements: 100 and 200.
v. print(max(tuple1))
The `max()` function returns the largest element.
Elements of tuple1: 23, 1, 45, 67, 45, 9, 55, 45. The maximum is 67.
vi. print(min(tuple1))
The `min()` function returns the smallest element.
Elements of tuple1: 23, 1, 45, 67, 45, 9, 55, 45. The minimum is 1.
vii. print(sum(tuple2))
The `sum()` function returns the sum of all elements.
viii. print(sorted(tuple1)) then print(tuple1)
The `sorted()` function returns a new sorted list from the tuple elements; the original tuple remains unchanged.
Sorted elements of tuple1 in ascending order: 1, 9, 23, 45, 45, 45, 55, 67.
```
Output of print(sorted(tuple1)): [1, 9, 23, 45, 45, 45, 55, 67]
Output of print(tuple1): (23, 1, 45, 67, 45, 9, 55, 45)
```
2Consider the following dictionary stateCapital:
stateCapital = {"AndhraPradesh": "Hyderabad", "Bihar": "Patna", "Maharashtra": "Mumbai", "Rajasthan": "Jaipur"}
Find the output of the following statements:
i. print(stateCapital.get("Bihar"))
ii. print(stateCapital.keys())
iii. print(stateCapital.values())
iv. print(stateCapital.items())
v. print(len(stateCapital))
vi. print("Maharashtra" in stateCapital)
vii. print(stateCapital.get("Assam"))
viii. del stateCapital["Rajasthan"] then print(stateCapital)Show solution
```python
stateCapital = {"AndhraPradesh": "Hyderabad",
"Bihar": "Patna",
"Maharashtra": "Mumbai",
"Rajasthan": "Jaipur"}
```
i. print(stateCapital.get("Bihar"))
The `get()` method returns the value associated with the given key.
Key "Bihar" maps to "Patna".
ii. print(stateCapital.keys())
The `keys()` method returns a view object containing all the keys of the dictionary.
iii. print(stateCapital.values())
The `values()` method returns a view object containing all the values of the dictionary.
iv. print(stateCapital.items())
The `items()` method returns a view object containing all key-value pairs as tuples.
v. print(len(stateCapital))
The `len()` function returns the number of key-value pairs in the dictionary.
There are 4 key-value pairs.
vi. print("Maharashtra" in stateCapital)
The `in` operator checks whether the given key exists in the dictionary.
"Maharashtra" is indeed a key in stateCapital, so the result is True.
vii. print(stateCapital.get("Assam"))
The `get()` method returns None if the key does not exist (instead of raising a KeyError).
"Assam" is not a key in stateCapital.
viii. del stateCapital["Rajasthan"] then print(stateCapital)
The `del` statement removes the key-value pair with key "Rajasthan" from the dictionary.
After deletion:
3"Lists and Tuples are ordered". Explain.Show solution
A sequence is said to be ordered if each element in it has a fixed position (index), and the order in which elements are stored is maintained throughout the lifetime of the object.
Both Lists and Tuples are ordered because:
1. Every element is assigned a definite index starting from 0 (positive indexing) or −1 from the end (negative indexing).
2. The elements are stored and retrieved in the same order in which they were inserted.
3. Two lists/tuples with the same elements but in different order are considered different.
Example:
```python
list1 = [10, 20, 30]
list2 = [30, 20, 10]
print(list1 == list2) # Output: False (order matters)
tuple1 = (10, 20, 30)
tuple2 = (30, 20, 10)
print(tuple1 == tuple2) # Output: False (order matters)
print(list1[0]) # Output: 10 (fixed position)
print(tuple1[2]) # Output: 30 (fixed position)
```
Because each element occupies a fixed, well-defined position, both lists and tuples are called ordered data structures. This is in contrast to dictionaries (in older Python versions) and sets, which do not guarantee element order.
4With the help of an example show how can you return more than one value from a function.Show solution
Example Program:
```python
def calculate(a, b):
"""Returns sum, difference, product and quotient of two numbers."""
total = a + b
difference = a - b
product = a * b
quotient = a / b
return total, difference, product, quotient # returns a tuple
# Calling the function
s, d, p, q = calculate(20, 4)
print("Sum =", s) # 24
print("Difference =", d) # 16
print("Product =", p) # 80
print("Quotient =", q) # 5.0
```
Output:
```
Sum = 24
Difference = 16
Product = 80
Quotient = 5.0
```
Explanation:
- The `return` statement packs all four values into a tuple `(24, 16, 80, 5.0)` automatically.
- On the calling side, tuple unpacking assigns each value to the corresponding variable.
- This is the standard Pythonic way to return more than one value from a function.
5What advantages do tuples have over lists?Show solution
| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable (cannot be changed) | Mutable (can be changed) |
| Speed | Faster to create and access | Slightly slower |
| Memory | Consumes less memory | Consumes more memory |
| Safety | Data is write-protected | Data can be accidentally modified |
| Use as dict key | Can be used as dictionary key | Cannot be used as dictionary key |
| Hashable | Yes | No |
Detailed Advantages:
1. Immutability / Data Integrity: Since tuples cannot be modified after creation, they protect data from accidental changes. This makes them ideal for storing constant or read-only data (e.g., days of the week, coordinates).
2. Faster Execution: Iterating over a tuple is faster than iterating over a list of the same size because Python can optimise immutable objects.
3. Less Memory: Tuples occupy less memory space compared to lists.
```python
import sys
print(sys.getsizeof((1,2,3))) # smaller
print(sys.getsizeof([1,2,3])) # larger
```
4. Can be used as Dictionary Keys: Because tuples are hashable (immutable), they can serve as keys in a dictionary, whereas lists cannot.
```python
location = {(28.6, 77.2): "Delhi"} # valid
```
5. Safe for Unpacking / Multiple Return Values: Functions commonly use tuples to return multiple values safely.
6. Can be stored in sets: Tuples can be elements of a set; lists cannot.
6When to use tuple or dictionary in Python. Give some examples of programming situations mentioning their usefulness.Show solution
Use a tuple when:
- The data should not change after creation (immutable, read-only data).
- You need to use the collection as a dictionary key.
- You want faster access and less memory usage.
- You are returning multiple values from a function.
- The data represents a fixed record (like a row in a database).
Examples of Tuple usage:
```python
# 1. Storing fixed data — days of the week
days = ('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday')
# 2. Geographic coordinates (should not change)
delhi_coords = (28.6139, 77.2090)
# 3. Returning multiple values from a function
def min_max(lst):
return min(lst), max(lst) # returns a tuple
# 4. RGB colour values
red = (255, 0, 0)
```
---
When to use a Dictionary:
Use a dictionary when:
- Data is in key-value pairs and you need fast lookup by key.
- Keys are unique identifiers (like roll numbers, usernames, product IDs).
- You need to map one piece of information to another.
- The data needs to be updated frequently.
Examples of Dictionary usage:
```python
# 1. Student records — roll number mapped to name
students = {101: 'Aman', 102: 'Priya', 103: 'Rahul'}
# 2. Phone book — name mapped to phone number
phonebook = {'Aman': '9876543210', 'Priya': '9123456789'}
# 3. Word frequency count
sentence = 'to be or not to be'
freq = {}
for word in sentence.split():
freq[word] = freq.get(word, 0) + 1
# freq = {'to': 2, 'be': 2, 'or': 1, 'not': 1}
# 4. State and capital mapping
state_capital = {'Rajasthan': 'Jaipur', 'Bihar': 'Patna'}
```
Summary: Use a tuple for fixed, ordered, immutable collections; use a dictionary for fast, key-based lookup of mutable, unordered key-value data.
7Prove with the help of an example that the variable is rebuilt in case of immutable data types.Show solution
We can verify this using the built-in `id()` function, which returns the memory address of an object.
Example with an integer (immutable):
```python
a = 10
print("Before modification:")
print("Value of a =", a)
print("id of a =", id(a))
a = a + 5 # 'modifying' a
print("\nAfter modification:")
print("Value of a =", a)
print("id of a =", id(a))
```
Sample Output:
```
Before modification:
Value of a = 10
id of a = 140720000000000
After modification:
Value of a = 15
id of a = 140720000000160
```
Observation: The `id` (memory address) of `a` changed after the assignment. This proves that a new integer object with value 15 was created and `a` now points to it. The old object (10) was not modified.
Example with a tuple (immutable):
```python
t = (1, 2, 3)
print("Before:", t, "id =", id(t))
t = t + (4,) # creates a new tuple
print("After: ", t, "id =", id(t))
```
Sample Output:
```
Before: (1, 2, 3) id = 2345678901
After: (1, 2, 3, 4) id = 2345679999
```
Conclusion: Every time we appear to 'change' an immutable variable, Python rebuilds (creates a new object) and reassigns the variable to the new object. The identity (`id`) changes, proving that the original object was not modified — it was replaced.
8TypeError occurs while statement 2 is running. Give reason. How can it be corrected?
>>> tuple1 = (5) #statement 1
>>> len(tuple1) #statement 2Show solution
```python
>>> tuple1 = (5) # statement 1
>>> len(tuple1) # statement 2
```
Reason for TypeError:
In statement 1, `tuple1 = (5)` does not create a tuple. Python treats `(5)` as simply the integer `5` enclosed in parentheses (for grouping), not as a tuple. Therefore, `tuple1` is of type int, not tuple.
We can verify:
```python
>>> type(tuple1)
<class 'int'>
```
In statement 2, `len(tuple1)` is called on an integer object. The `len()` function works only on sequences (strings, lists, tuples, etc.) and not on scalar types like `int`. Hence Python raises:
```
TypeError: object of type 'int' has no len()
```
Correction:
To create a single-element tuple, a trailing comma must be placed inside the parentheses:
```python
>>> tuple1 = (5,) # correct way to create a single-element tuple
>>> type(tuple1)
<class 'tuple'>
>>> len(tuple1)
1
```
Rule: A single-element tuple must always have a trailing comma — `(element,)` — otherwise Python interprets it as a parenthesised expression, not a tuple.
Programming Problems
1Write a program to read email IDs of n number of students and store them in a tuple. Create two new tuples, one to store only the usernames from the email IDs and second to store domain names from the email IDs. Print all three tuples at the end of the program. [Hint: You may use the function split()]Show solution
```python
# Program to split email IDs into usernames and domain names
n = int(input("Enter the number of students: "))
email_list = []
for i in range(n):
email = input(f"Enter email ID of student {i+1}: ")
email_list.append(email)
# Convert list to tuple
email_tuple = tuple(email_list)
# Create username and domain tuples
username_list = []
domain_list = []
for email in email_tuple:
parts = email.split('@') # splits into [username, domain]
username_list.append(parts[0])
domain_list.append(parts[1])
username_tuple = tuple(username_list)
domain_tuple = tuple(domain_list)
# Display all three tuples
print("\nAll Email IDs :", email_tuple)
print("Usernames :", username_tuple)
print("Domain Names :", domain_tuple)
```
Sample Run:
```
Enter the number of students: 3
Enter email ID of student 1: alice@gmail.com
Enter email ID of student 2: bob@yahoo.com
Enter email ID of student 3: carol@cbse.nic.in
All Email IDs : ('alice@gmail.com', 'bob@yahoo.com', 'carol@cbse.nic.in')
Usernames : ('alice', 'bob', 'carol')
Domain Names : ('gmail.com', 'yahoo.com', 'cbse.nic.in')
```
2Write a program to input names of n students and store them in a tuple. Also, input a name from the user and find if this student is present in the tuple or not.Show solution
```python
# Program to search a student name in a tuple
n = int(input("Enter the number of students: "))
name_list = []
for i in range(n):
name = input(f"Enter name of student {i+1}: ")
name_list.append(name)
# Convert list to tuple
student_tuple = tuple(name_list)
print("\nStudent Tuple:", student_tuple)
# Search for a student
search_name = input("\nEnter the name to search: ")
if search_name in student_tuple:
print(f"{search_name} is PRESENT in the tuple.")
else:
print(f"{search_name} is NOT PRESENT in the tuple.")
```
Sample Run:
```
Enter the number of students: 4
Enter name of student 1: Aman
Enter name of student 2: Priya
Enter name of student 3: Rahul
Enter name of student 4: Sneha
Student Tuple: ('Aman', 'Priya', 'Rahul', 'Sneha')
Enter the name to search: Rahul
Rahul is PRESENT in the tuple.
```
3Write a Python program to find the highest 2 values in a dictionary.Show solution
```python
# Program to find the highest 2 values in a dictionary
# Sample dictionary
marks = {'Aman': 85, 'Priya': 92, 'Rahul': 78, 'Sneha': 95, 'Karan': 88}
print("Dictionary:", marks)
# Method: sort values in descending order and take first two
sorted_values = sorted(marks.values(), reverse=True)
top2 = sorted_values[:2]
print("\nTop 2 highest values:", top2)
# Also display which students have these top 2 values
print("\nStudents with top 2 values:")
for key, value in marks.items():
if value in top2:
print(f" {key}: {value}")
```
Output:
```
Dictionary: {'Aman': 85, 'Priya': 92, 'Rahul': 78, 'Sneha': 95, 'Karan': 88}
Top 2 highest values: [95, 92]
Students with top 2 values:
Priya: 92
Sneha: 95
```
4Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string: 'w3resource'
Expected output: {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}Show solution
```python
# Program to create a frequency dictionary from a string
string = input("Enter a string: ")
freq_dict = {}
for char in string:
freq_dict[char] = freq_dict.get(char, 0) + 1
print("Frequency Dictionary:", freq_dict)
```
Sample Run:
```
Enter a string: w3resource
Frequency Dictionary: {'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}
```
Step-by-step trace for 'w3resource':
| Character | Action | Dictionary state |
|---|---|---|
| w | new key, count=1 | {'w':1} |
| 3 | new key, count=1 | {'w':1,'3':1} |
| r | new key, count=1 | {...,'r':1} |
| e | new key, count=1 | {...,'e':1} |
| s | new key, count=1 | {...,'s':1} |
| o | new key, count=1 | {...,'o':1} |
| u | new key, count=1 | {...,'u':1} |
| r | existing, count+1 | {...,'r':2} |
| c | new key, count=1 | {...,'c':1} |
| e | existing, count+1 | {...,'e':2} |
Final dictionary matches the expected output.
5Write a program to input your friends' names and their Phone Numbers and store them in the dictionary as the key-value pair. Perform the following operations on the dictionary:
a) Display the name and phone number of all your friends
b) Add a new key-value pair in this dictionary and display the modified dictionary
c) Delete a particular friend from the dictionary
d) Modify the phone number of an existing friend
e) Check if a friend is present in the dictionary or not
f) Display the dictionary in sorted order of namesShow solution
```python
# Program to manage a friends' phone book using a dictionary
# Step 1: Input friends' names and phone numbers
phonebook = {}
n = int(input("Enter number of friends: "))
for i in range(n):
name = input(f"Enter name of friend {i+1}: ")
phone = input(f"Enter phone number of {name}: ")
phonebook[name] = phone
# a) Display all friends and their phone numbers
print("\na) All Friends and Phone Numbers:")
for name, phone in phonebook.items():
print(f" {name}: {phone}")
# b) Add a new key-value pair
new_name = input("\nb) Enter name of new friend to add: ")
new_phone = input(f" Enter phone number of {new_name}: ")
phonebook[new_name] = new_phone
print(" Modified Dictionary:", phonebook)
# c) Delete a particular friend
del_name = input("\nc) Enter name of friend to delete: ")
if del_name in phonebook:
del phonebook[del_name]
print(f" {del_name} deleted. Updated Dictionary:", phonebook)
else:
print(f" {del_name} not found in phonebook.")
# d) Modify the phone number of an existing friend
mod_name = input("\nd) Enter name of friend whose number is to be modified: ")
if mod_name in phonebook:
new_num = input(f" Enter new phone number for {mod_name}: ")
phonebook[mod_name] = new_num
print(" Updated Dictionary:", phonebook)
else:
print(f" {mod_name} not found in phonebook.")
# e) Check if a friend is present
check_name = input("\ne) Enter name to check: ")
if check_name in phonebook:
print(f" {check_name} IS present in the phonebook.")
else:
print(f" {check_name} is NOT present in the phonebook.")
# f) Display in sorted order of names
print("\nf) Phonebook in Sorted Order of Names:")
for name in sorted(phonebook.keys()):
print(f" {name}: {phonebook[name]}")
```
Sample Run:
```
Enter number of friends: 3
Enter name of friend 1: Priya
Enter phone number of Priya: 9876543210
Enter name of friend 2: Aman
Enter phone number of Aman: 9123456789
Enter name of friend 3: Sneha
Enter phone number of Sneha: 9988776655
a) All Friends and Phone Numbers:
Priya: 9876543210
Aman: 9123456789
Sneha: 9988776655
b) Enter name of new friend to add: Rahul
Enter phone number of Rahul: 9001122334
Modified Dictionary: {'Priya': '9876543210', 'Aman': '9123456789', 'Sneha': '9988776655', 'Rahul': '9001122334'}
c) Enter name of friend to delete: Sneha
Sneha deleted. Updated Dictionary: {'Priya': '9876543210', 'Aman': '9123456789', 'Rahul': '9001122334'}
d) Enter name of friend whose number is to be modified: Aman
Enter new phone number for Aman: 9000000001
Updated Dictionary: {'Priya': '9876543210', 'Aman': '9000000001', 'Rahul': '9001122334'}
e) Enter name to check: Priya
Priya IS present in the phonebook.
f) Phonebook in Sorted Order of Names:
Aman: 9000000001
Priya: 9876543210
Rahul: 9001122334
```
Case Study-Based Question (SMIS System)
1Write a program to take in the roll number, name and percentage of marks for n students of Class X. Write user defined functions to:
- accept details of the n students
- search details of a particular student on the basis of roll number and display result
- display the result of all the students
- find the topper amongst them
- find the subject toppers amongst them
(Hint: use Dictionary, where the key can be roll number and the value is an immutable data type containing name and percentage)Show solution
```python
# SMIS - Student Management and Information System
# Dictionary: {roll_number: (name, percentage)}
students = {} # global dictionary
# -------------------------------------------------------
# Function 1: Accept details of n students
# -------------------------------------------------------
def accept_details():
n = int(input("Enter number of students: "))
for i in range(n):
roll = int(input(f"\nEnter Roll Number of student {i+1}: "))
name = input("Enter Name: ")
perc = float(input("Enter Percentage: "))
students[roll] = (name, perc) # value is a tuple (immutable)
print("\nDetails accepted successfully.")
# -------------------------------------------------------
# Function 2: Search a student by roll number
# -------------------------------------------------------
def search_student():
roll = int(input("Enter Roll Number to search: "))
if roll in students:
name, perc = students[roll]
print(f"Roll No : {roll}")
print(f"Name : {name}")
print(f"Percent : {perc}%")
if perc >= 33:
print("Result : PASS")
else:
print("Result : FAIL")
else:
print("Student with this roll number NOT FOUND.")
# -------------------------------------------------------
# Function 3: Display result of all students
# -------------------------------------------------------
def display_all():
if not students:
print("No student records found.")
return
print(f"\n{'Roll':<8}{'Name':<20}{'Percentage':<12}{'Result'}")
print("-" * 50)
for roll, (name, perc) in students.items():
result = "PASS" if perc >= 33 else "FAIL"
print(f"{roll:<8}{name:<20}{perc:<12}{result}")
# -------------------------------------------------------
# Function 4: Find the topper (highest percentage)
# -------------------------------------------------------
def find_topper():
if not students:
print("No student records found.")
return
topper_roll = max(students, key=lambda r: students[r][1])
name, perc = students[topper_roll]
print(f"\nTopper Details:")
print(f"Roll No : {topper_roll}")
print(f"Name : {name}")
print(f"Percentage : {perc}%")
# -------------------------------------------------------
# Function 5: Find subject toppers
# (Accepts subject-wise marks separately)
# -------------------------------------------------------
def find_subject_toppers():
subjects = ['English', 'Hindi', 'Maths', 'Science', 'Social Science']
# subject_marks: {roll: [marks list]}
subject_marks = {}
print("\nEnter subject-wise marks for each student:")
for roll, (name, _) in students.items():
print(f"\nStudent: {name} (Roll: {roll})")
marks = []
for sub in subjects:
m = float(input(f" {sub}: "))
marks.append(m)
subject_marks[roll] = marks
print("\nSubject Toppers:")
for idx, sub in enumerate(subjects):
topper_roll = max(subject_marks, key=lambda r: subject_marks[r][idx])
topper_name = students[topper_roll][0]
top_marks = subject_marks[topper_roll][idx]
print(f" {sub:<20}: {topper_name} (Roll {topper_roll}) with {top_marks} marks")
# -------------------------------------------------------
# Main Menu
# -------------------------------------------------------
def main():
while True:
print("\n===== SMIS - Student Management System =====")
print("1. Accept Student Details")
print("2. Search Student by Roll Number")
print("3. Display All Students' Results")
print("4. Find Topper")
print("5. Find Subject Toppers")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1: accept_details()
elif choice == 2: search_student()
elif choice == 3: display_all()
elif choice == 4: find_topper()
elif choice == 5: find_subject_toppers()
elif choice == 6:
print("Exiting SMIS. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
main()
```
Key Design Decisions:
- Dictionary key = roll number (unique identifier).
- Dictionary value = tuple `(name, percentage)` — immutable as required by the hint.
- Each functionality is encapsulated in a separate user-defined function.
- Pass mark is taken as 33%.
- The topper is found using `max()` with a lambda key on percentage.
Stuck on a step?
Ask Super Tutor AI to explain any solution on this page in a simpler way — free, 24x7.
Ask a Doubt FreeFrequently Asked Questions
What are the important topics in Tuples and Dictionaries for Jharkhand Board Class 11 Computer Science?
How to score full marks in Tuples and Dictionaries — Jharkhand Board Class 11 Computer Science?
Where can I get free NCERT Solutions for Tuples and Dictionaries Class 11 Computer Science?
Sources & Official References
Content is aligned to the official syllabus. Refer to the board website for the latest curriculum.
More resources for Tuples and Dictionaries
Important Questions
Practice with board exam-style questions
Syllabus
What topics to cover
Revision Notes
Key points for last-minute revision
Study Plan
Step-by-step plan to ace this chapter
Flashcards
Quick-fire cards for active recall
Formula Sheet
All formulas in one place
Chapter Summary
Understand the chapter at a glance
Practice Quiz
Test yourself with a quick quiz
Concept Maps
See how topics connect visually
For serious students
Get the full Tuples and Dictionaries chapter — for free.
Quizzes, flashcards, AI doubt-solver and a step-by-step study plan for Jharkhand Board Class 11 Computer Science.