CBSE Class 11 CS (083) - Dictionary

Dictionary in Python

A dictionary is an unordered, mutable collection of key-value pairs. Each element has a unique key and an associated value. This chapter covers all dictionary operations as per the CBSE Class 11 Computer Science syllabus.

1. Introduction to Dictionary

A dictionary is a collection of key-value pairs enclosed in curly braces {}. Each key is unique and maps to a value. Keys must be immutable (strings, numbers, tuples); values can be any data type.

Dictionaries are mutable — you can add, modify, or delete key-value pairs.

Dictionaries are also called associative arrays or hash maps in other languages.

2. Creating Dictionaries

# Empty dictionary
empty = {}

# Using curly braces
student = {"name": "Riya", "age": 17, "class": "11th"}

3. Accessing Values

# Access by key
student = {"name": "Riya", "age": 17, "class": "11th"}
print(student["name"]) # Riya

# get() method (safe — no KeyError)
print(student.get("name")) # Riya
print(student.get("city")) # None
print(student.get("city", "N/A")) # N/A

4. Modifying Dictionaries

student = {"name": "Riya", "age": 17}

# Add new key-value pair
student["class"] = "11th"
# student: {"name": "Riya", "age": 17, "class": "11th"}

# Update existing value
student["age"] = 18

# Delete using del
del student["class"]

5. Dictionary Methods

MethodDescriptionExampleResult
keys()Returns all keysd.keys()dict_keys([...])
values()Returns all valuesd.values()dict_values([...])
items()Returns all (key, value) pairsd.items()dict_items([(k,v),...])
get(key, default)Returns value for key or defaultd.get("x", 0)0
update(dict2)Updates with another dictd.update({"a":1})Merges dict2
pop(key)Removes and returns valued.pop("key")Removes key
popitem()Removes last inserted (key,value)d.popitem()Tuple (k,v)
clear()Removes all itemsd.clear(){}
copy()Returns a shallow copyd.copy()New dict
fromkeys(seq, val)Creates dict from sequencedict.fromkeys("abc",0){"a":0,"b":0,"c":0}
setdefault(key, val)Returns value; sets if missingd.setdefault("k",0)0 added

6. Traversing a Dictionary

student = {"name": "Riya", "age": 17, "class": "11th"}

# Traverse keys
for key in student:
print(key, ":", student[key])

# Traverse using items()
for key, value in student.items():
print(f"{key}: {value}")

7. Keys in Dictionary

# Keys must be immutable
d = {
"name": "Riya", # string key
1: "one", # integer key
(1, 2): "tuple" # tuple key
}
# d = {[1,2]: "list"} # TypeError: unhashable type: 'list'

# Check if key exists
print("name" in d) # True
print(5 not in d) # True

8. Nested Dictionaries

students = {
101: {"name": "Riya", "marks": 85},
102: {"name": "Amit", "marks": 92},
103: {"name": "Priya", "marks": 78}
}

print(students[101]) # {"name": "Riya", "marks": 85}
print(students[102]["name"]) # Amit

for roll, info in students.items():
print(f"Roll {roll}: {info['name']} scored {info['marks']}")

9. Dictionary Comprehension

# Squares of numbers
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Even squares only
squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(squares) # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# Reverse key-value
d = {"a": 1, "b": 2}
rev = {v: k for k, v in d.items()}
print(rev) # {1: 'a', 2: 'b'}

10. Built-in Functions with Dictionary

FunctionDescriptionExampleResult
len(d)Number of key-value pairslen({1:2,3:4})2
any(d)True if any key is Trueany({0:1,1:2})True
all(d)True if all keys are Trueall({1:2,0:3})False
sorted(d)Returns sorted list of keyssorted({3:1,1:2})[1, 3]

11. Revision Questions and Answers

Very Short Answer Questions

1. What is a dictionary in Python?
An unordered, mutable collection of key-value pairs.

2. Can a list be used as a dictionary key? Why?
No, because lists are mutable and not hashable.

3. Which method returns all keys of a dictionary?
keys().

4. What does get() return if the key is not found?
None (or a default value if provided).

5. How do you check if a key exists in a dictionary?
Using the "in" operator.

Short Answer Questions

1. Differentiate between del and pop() for dictionary.
del removes a key-value pair without returning the value. pop() removes and returns the value. If the key doesn't exist, del raises KeyError, while pop() can return a default value.

2. Explain dictionary comprehension with an example.
Dictionary comprehension creates dictionaries concisely: {key: value for item in iterable}. Example: {x: x**2 for x in range(1, 5)} produces {1:1, 2:4, 3:9, 4:16}.

Long Answer Questions

1. Write a Python program to count the frequency of each character in a string using a dictionary.
text = input("Enter string: "); freq = {}; for ch in text: freq[ch] = freq.get(ch, 0) + 1; print(freq)

2. Write a program to store student records (roll_no as key, name and marks as value) and display all students who scored above 80.
students = {101: {"name":"Riya","marks":85}, 102: {"name":"Amit","marks":92}, 103: {"name":"Priya","marks":78}}; for roll, info in students.items(): if info["marks"] > 80: print(f"{info['name']} (Roll: {roll}) - {info['marks']}")