Tuples and Dictionaries — NCERT Class 11 Computer Science Exercise Solutions
How to Use This Page
Attempt each question on your own before reading the solution. Type the code in your Python IDE and run it. Compare the output with what is shown here. If you get an error, read the error message carefully — it usually tells you exactly what went wrong. For exam preparation, time yourself and try to write the code without looking at hints.
Key Concepts Recap
Before starting the exercises, review these essentials:
- Tuples: ordered, immutable, created with
(), single-element needs comma(5,), methods:count()andindex() - Tuple functions:
len(),min(),max(),sum(),sorted(),tuple() - Tuple unpacking:
a, b, c = (1, 2, 3) - Dictionaries: key-value pairs, keys must be unique and immutable, created with
{}ordict() - Dictionary access:
dict["key"](raises KeyError) vsdict.get("key")(returns None) - Dictionary methods:
keys(),values(),items(),get(),update(),pop(),popitem(),clear(),setdefault(),fromkeys() - Creating dict from two lists:
dict(zip(keys, values)) inoperator checks keys in a dictionary, not values
Exercise Questions and Answers
Q1. Create a tuple with five elements of different data types. Print each element along with its type.
mixed = (10, "hello", 3.14, True, None)
for item in mixed:
print(f"Value: {item}, Type: {type(item).__name__}")
Output:
Q2. Demonstrate the difference between (5) and (5,). Show their types and explain why.
a = (5)
b = (5,)
print("a = (5)")
print(f" Value: {a}")
print(f" Type: {type(a).__name__}") # int
print("b = (5,)")
print(f" Value: {b}")
print(f" Type: {type(b).__name__}") # tuple
Output:
Q3. Given the tuple t = (10, 20, 30, 20, 40, 20, 50), find: (a) How many times 20 appears, (b) The index of the first 20, (c) The index of 20 starting from position 3.
t = (10, 20, 30, 20, 40, 20, 50)
# (a) Count of 20
print("Count of 20:", t.count(20)) # 3
# (b) Index of first 20
print("First index of 20:", t.index(20)) # 1
# (c) Index of 20 starting from position 3
print("Index of 20 from pos 3:", t.index(20, 3)) # 5
Output:
Q4. Create a dictionary to store student details (name, age, class, marks). Then: (a) Add a new key "city", (b) Update the marks, (c) Delete the age key, (d) Print all key-value pairs.
student = {"name": "Rahul", "age": 17, "class": "11", "marks": 88}
print("Original:", student)
# (a) Add a new key "city"
student["city"] = "Delhi"
print("After adding city:", student)
# (b) Update the marks
student["marks"] = 95
print("After updating marks:", student)
# (c) Delete the age key
del student["age"]
print("After deleting age:", student)
# (d) Print all key-value pairs
print("\nAll key-value pairs:")
for key, value in student.items():
print(f" {key}: {value}")
Output:
Q5. Explain the difference between accessing a dictionary value using dict["key"] and dict.get("key"). Write a program that demonstrates both.
student = {"name": "Priya", "age": 16, "marks": 92}
# Using square bracket notation
print("Using dict['name']:", student["name"]) # Priya
# Using get() method
print("Using dict.get('name'):", student.get("name")) # Priya
# Key that does NOT exist
# print(student["grade"]) # This would raise KeyError
print("Using dict.get('grade'):", student.get("grade")) # None
print("Using dict.get('grade', 'N/A'):", student.get("grade", "N/A")) # N/A
Output:
Q6. Write a program to merge two dictionaries. If a key exists in both, the value from the second dictionary should be kept.
dict1 = {"name": "Rahul", "age": 17, "marks": 88}
dict2 = {"marks": 95, "city": "Delhi", "grade": "A"}
print("Dictionary 1:", dict1)
print("Dictionary 2:", dict2)
# Method 1: using update()
merged = dict1.copy()
merged.update(dict2)
print("Merged (update):", merged)
# {'name': 'Rahul', 'age': 17, 'marks': 95, 'city': 'Delhi', 'grade': 'A'}
# Method 2: using dictionary unpacking
merged2 = {**dict1, **dict2}
print("Merged (unpacking):", merged2)
# {'name': 'Rahul', 'age': 17, 'marks': 95, 'city': 'Delhi', 'grade': 'A'}
Note: The value of "marks" from dict2 (95) overwrites the value from dict1 (88).
Output:
Q7. Write a program to count the frequency of each word in a given sentence using a dictionary.
sentence = "the quick brown fox jumps over the lazy dog the fox was quick"
words = sentence.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print("Word frequencies:")
for word in sorted(freq):
print(f" {word}: {freq[word]}")
Output:
Q8. Demonstrate that tuples are immutable. Try to modify a tuple element and show the error. Then show the workaround.
t = (1, 2, 3, 4, 5)
print("Original tuple:", t)
# Attempt to modify — this will raise TypeError
try:
t[2] = 99
except TypeError as e:
print("Error when modifying:", e)
# 'tuple' object does not support item assignment
# Workaround: convert to list, modify, convert back
temp = list(t)
temp[2] = 99
t = tuple(temp)
print("After workaround:", t) # (1, 2, 99, 4, 5)
Output:
Q9. Create a dictionary from two separate lists — one of names and one of scores. Then find the student with the highest score.
names = ["Rahul", "Priya", "Amit", "Sneha", "Karthik"]
scores = [88, 92, 95, 87, 91]
# Create dictionary using zip()
result = dict(zip(names, scores))
print("Score sheet:", result)
# Find student with highest score
topper = max(result, key=result.get)
print(f"Topper: {topper} with {result[topper]} marks")
# Alternative: manual method
highest = -1
top_student = ""
for name, score in result.items():
if score > highest:
highest = score
top_student = name
print(f"Topper (manual): {top_student} with {highest} marks")
Output:
Q10. Given a nested dictionary of students and their marks in different subjects, write a program to: (a) Print each student's average marks, (b) Find the overall topper.
students = {
"Rahul": {"math": 88, "science": 92, "english": 85},
"Priya": {"math": 95, "science": 89, "english": 91},
"Amit": {"math": 78, "science": 85, "english": 90}
}
averages = {}
# (a) Print each student's average marks
print("Student averages:")
for name, marks in students.items():
avg = sum(marks.values()) / len(marks)
averages[name] = avg
print(f" {name}: {avg:.2f}")
# (b) Find the overall topper
topper = max(averages, key=averages.get)
print(f"\nTopper: {topper} with average {averages[topper]:.2f}")
Output:
Related Chapters
- [CBSE Class 11 Computer Science Chapter 10 — Tuples and Dictionaries (Chapter Guide)](/class/11/computer-science/cbse-tuples-and-dictionaries) — full concept notes with definitions, methods, and exam tips
- [CBSE Class 11 Computer Science Chapter 9 — Lists (Chapter Guide)](/class/11/computer-science/cbse-lists) — previous chapter concepts
- [CBSE Class 11 Computer Science Chapter 9 — Lists Exercise Solutions](/class/11/computer-science/solutions/cbse-lists-exercise-solutions) — practice the previous chapter
