Unit 2: Computational Thinking & Programming
Chapter 8: Dictionaries in Python
1. Introduction to Dictionaries
A Dictionary is an unordered (insertion-ordered since Python 3.7), mutable collection of Key-Value pairs enclosed in curly braces {}.
$$\text{Dictionary} = {\text{key}_1: \text{value}_1, \text{key}_2: \text{value}_2, \dots}$$
Rules for Dictionary Keys:
- Keys must be of an immutable data type (e.g.,
int,float,str,tuple). Alistordictcannot be a key. - Keys must be unique. If duplicate keys are specified, the last value overwrites previous ones.
- Values can be of any data type (mutable, immutable, nested) and can repeat.
# Valid dictionary
student = {
"roll_no": 101,
"name": "Diya",
"subjects": ["Physics", "Chemistry", "CS"],
"percentage": 94.2
}
2. Accessing, Adding, and Modifying Items
Accessing Values
- Square Bracket Notation
d[key]: Returns value; raisesKeyErrorif key does not exist. - The
get(key[, default])Method: Returns value; returnsdefault(orNone) if key is absent without throwing an error.
d = {"CS": 83, "IP": 65, "Math": 41}
print(d["CS"]) # 83
print(d.get("Physics", 0)) # 0 (Safe access)
Adding and Modifying Key-Value Pairs
d["English"] = 92 # Adds new key "English"
d["CS"] = 99 # Modifies existing key "CS"
Deleting Items
del d[key]: Deletes specified key-value pair.d.pop(key): Removes key and returns its associated value.d.popitem(): Removes and returns the last inserted(key, value)tuple.d.clear(): Empties the dictionary completely.
3. Built-in Dictionary Methods
| Method | Description | Example |
|---|---|---|
len(d) |
Number of key-value pairs. | len({"a": 1, "b": 2}) $\to$ 2 |
d.keys() |
Returns a view object of all keys. | d.keys() $\to$ dict_keys(['a', 'b']) |
d.values() |
Returns a view object of all values. | d.values() $\to$ dict_values([1, 2]) |
d.items() |
Returns view object of (key, value) tuples. |
d.items() $\to$ dict_items([('a', 1), ...]) |
d.update(other) |
Merges another dictionary or key-value pairs. | d.update({"c": 3}) |
key in d |
Checks if key exists in dictionary. |
'a' in d $\to$ True |
4. Iterating Over a Dictionary
scores = {"Amit": 88, "Sneha": 95, "Rohit": 78}
# 1. Iterating over keys
for name in scores:
print(name, "->", scores[name])
# 2. Iterating over keys and values simultaneously
for name, marks in scores.items():
print(f"Student: {name:8} Marks: {marks}")
5. Classic Dictionary Programs for Practical Exams
Program 1: Frequency Count of Words in a Sentence
sentence = input("Enter a sentence: ").lower()
words = sentence.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
for word, count in freq.items():
print(f"'{word}': {count}")
Program 2: Student Marks and Highest Scorer
n = int(input("Enter number of students: "))
students = {}
for _ in range(n):
name = input("Enter student name: ")
marks = float(input(f"Enter marks for {name}: "))
students[name] = marks
# Find topper
topper = max(students, key=students.get)
print(f"Class Topper: {topper} with {students[topper]} marks!")
6. Board Exam Practice Questions & Solutions
Q1. Identify which of the following are valid keys in a Python dictionary:
1. 45
2. 'roll_no'
3. [1, 2, 3]
4. (1, 2, 3)
5. {"a": 1}
Answer:
- 45: Valid (integer is immutable).
- 'roll_no': Valid (string is immutable).
- [1, 2, 3]: Invalid (list is mutable and cannot be hashed).
- (1, 2, 3): Valid (tuple with immutable contents is immutable).
- {"a": 1}: Invalid (dict is mutable).
Q2. Find the output of the following code:
inventory = {"Pen": 50, "Pencil": 30, "Notebook": 20}
inventory["Pencil"] = 45
inventory["Eraser"] = 15
print("Items:", len(inventory))
print("Pencil count:", inventory.get("Pencil"))
print("Ruler count:", inventory.get("Ruler", 0))
Answer:
Items: 4
Pencil count: 45
Ruler count: 0