1. Introduction: Why Dictionaries are Your New Best Friend
Hello, future coders! After two decades of teaching Python, I’ve seen students struggle with “finding” data in large lists. Imagine having a school with 1,000 lockers. If you had to check every single locker starting from number 1 just to find your bag, you’d be exhausted! Instead, you use a unique Locker Key.
In Python, most collections like Strings and Lists are Sequences—they rely on numeric positions (0, 1, 2…). Dictionaries, however, are Mappings. They link a unique “Key” to a specific “Value.” This chapter is a scoring powerhouse for Class 11 exams and competitive tests like CUET because it introduces you to the logic used in real-world databases.
——————————————————————————–
2. The Anatomy of a Dictionary: Key-Value Pairs
A dictionary stores data as key:value pairs. We call one such pair an item.
| Technical Term | What it Means in Simple English |
| Key | The unique “index” you create (like a Roll No. or Word). |
| Value | The data associated with that key (like a Student Name or Meaning). |
| Item | The complete pair of Key : Value. |
| Mapping | The internal link Python creates to connect a key to its value. |
The Syntax Checklist:
- Curly Braces: Dictionaries are always enclosed in
{}. - Colons: A colon
:separates the key from its value. - Commas: Each item (pair) is separated by a comma
,.
Example: emp = {"empno": 1, "name": "Shahrukh", "fee": 15000}
——————————————————————————–
3. The “Golden Rules” of Keys and Values
To score well in “Error Finding” questions, you must memorize these rules. They are the most common “traps” in exams.
| Feature | Dictionary Keys | Dictionary Values |
| Data Type | Must be Immutable (String, Number, or Tuple). | Can be Any data type (List, Dict, etc.). |
| Uniqueness | Must be Unique. No duplicates allowed. | Can be repeated. |
| Constraint | If a key is duplicated, the last value overwrites. | No constraints. |
⚠️ Teacher’s Warning (The TypeError Trap): If you try to use a List as a key (e.g., {[1,2]: "Error"}), Python will throw a TypeError: unhashable type: 'list'. This is because lists can change (mutable), and keys must be set in stone.
——————————————————————————–
4. Characteristics of Dictionaries: The Big Four
- Mappings, Not Sequences: Unlike lists, they are not accessed by numeric indices. They are indexed by keys.
- Mutable: You can change values or add new items “in-place” without creating a new dictionary.
- Modern Ordering: While traditionally unordered, Python 3.7+ maintains the order in which items are inserted.
- Dictionary vs. Sequence Table:
| Feature | Sequence (List/String) | Mapping (Dictionary) |
| Access Method | Numeric Index (0, 1, 2…) | User-defined Keys |
| Order | Positional | Insertion Order (3.7+) |
| Internal Logic | Offset-based | Hash-function based |
——————————————————————————–
5. How to Create Dictionaries (Multiple Methods)
There are five ways to build a dictionary. Note the syntax differences carefully!
- Empty Dictionary:
d = {}ord = dict() - Standard Initialization:
Student = {"roll": 1, "name": "Scott", "per": 90} - Using
dict()Constructor:Student = dict(roll=1, name='Scott', per=89)(Note: No quotes around keys when used as keyword arguments!) - Using
zip()to Pair Sequences:Emp = dict(zip(('empno', 'name'), (1, 'Scott'))) - Using a List of Tuples:
Emp = dict([('name', 'Victor'), ('dept', 'sales')])
——————————————————————————–
6. Accessing and Modifying Elements
- To Retrieve: Use
DictionaryName[key].print(emp['name'])→ Output:Shahrukh- Exam Alert: Accessing a non-existent key results in a KeyError.
- To Add/Modify: Both use the same syntax:
DictionaryName[key] = value.- If the key exists, the value is updated.
- If the key is new, a new item is added to the dictionary.
——————————————————————————–
7. Membership Testing and the ‘in’ Keyword
The in and not in operators are used to check existence.
- Rule: By default, they only check Keys.
'name' in emp→True15000 in emp→False(because 15000 is a value, not a key).- Workaround: To search values, use
if 15000 in emp.values():.
——————————————————————————–
8. Traversing a Dictionary: The ‘for’ Loop
Traversing means visiting every item.
- Looping through Keys (Default):
- Accessing Values:
- Looping through Items:
——————————————————————————–
9. Removing Items: The “Delete” Toolkit
Think of these as different ways to clean out your “lockers.”
| Method | Behavior | Returns |
del dict[key] | Deletes the specific key-value pair. | Nothing |
pop(key, msg) | Removes key and returns its value. | The Value |
popitem() | Removes the last inserted item (LIFO). | (Key, Value) Tuple |
clear() | Removes all items, leaving {}. | Nothing |
del dict | Deletes the entire object from memory. | N/A (Error if accessed) |
Pro Tip: pop() is safer than del because you can provide a default message: emp.pop('salary', 'Not Found'). This prevents a KeyError if the key is missing.
——————————————————————————–
10. Essential Built-in Functions & Methods
The Dictionary Power-User Table
| Method | Description | Example | Return Type |
len() | Returns number of items. | len(d) | Integer |
get(k, d) | The Safe Accessor: Returns value of k. If k is missing, returns d (or None). No Exception raised! | d.get('age', 'NA') | Value / Message |
keys() | Returns all keys as a sequence. | d.keys() | dict_keys view |
values() | Returns all values as a sequence. | d.values() | dict_values view |
items() | Returns (key, value) pairs as tuples. | d.items() | dict_items view |
update() | Merges two dictionaries. Overwrites existing keys with new values. | d1.update(d2) | None |
fromkeys() | Creates a new dict from a sequence of keys. | dict.fromkeys(seq, 0) | Dictionary |
max() / min() | Returns highest/lowest Value (if all types match). | max(d.values()) | Matching Type |
sorted() | Returns a sorted list of Keys by default. | sorted(d) | List |
⚠️ Student Trap (The fromkeys Sharing Error): If you use a mutable object like a list as a default value in fromkeys(), all keys will point to the same list object. If you update one, they all change! d = dict.fromkeys(['a', 'b'], []) d['a'].append(1) print(d) → {'a': [1], 'b': [1]}
——————————————————————————–
11. Advanced Concept: Nesting Dictionaries
A value inside a dictionary can itself be another dictionary.
Visitor = {
'Scott': {'City': 'Kanpur', 'Pin': '208004'},
'Peter': {'City': 'Delhi', 'Pin': '110001'}
}
Accessing Logic: To get Peter’s City, use double brackets: Visitor['Peter']['City'].
——————————————————————————–
12. Pretty Printing and the JSON Module
Standard print() output is messy. For large dictionaries, use the json module.
- Before:
{'a': 1, 'b': 2, 'c': 3} - After (Pretty):
——————————————————————————–
13. Logical Programming with Dictionaries
1. Word Frequency Counter (Exam Favorite!)
Using split() to break a sentence into words and count occurrences.
sentence = "Python is great and Python is fun"
words = sentence.split() # Breaks into list of words
d = {}
for w in words:
if w not in d:
d[w] = words.count(w)
print(d)
# Output: {'Python': 2, 'is': 2, 'great': 1, 'and': 1, 'fun': 1}
2. Employee Management System
emp_dict = {'empname': [], 'salary': []}
# Adding data
name = input("Enter name: ")
sal = int(input("Enter salary: "))
emp_dict['empname'].append(name)
emp_dict['salary'].append(sal)
# Searching data
search = input("Enter name to search: ")
if search in emp_dict['empname']:
pos = emp_dict['empname'].index(search)
print("Salary is:", emp_dict['salary'][pos])
else:
print("Record not found")
——————————————————————————–
14. Quick Revision Sheet
- Definition: Unordered collection of
key:valuepairs (Mappings). - Mutability: Dictionary is Mutable; Keys must be Immutable (String/Number/Tuple).
- Duplicate Keys: Overwritten by the last value assigned.
- Key Search:
inandnot incheck keys only. - Key Method Trio:
get()(Safe access),pop()(Remove & return),update()(Merge).
——————————————————————————–
15. Common Mistakes Students Make
- Index Error: Trying to use
dict[0]when0isn’t a key. - KeyError: Forgetting to check if a key exists before using
delorpop. - Mutable Key Error: Trying to use a
listas a key. - Clear vs Del:
clear()empties the container;deldestroys the whole container. - Value Search: Forgeting that
'val' in dreturnsFalseeven if the value exists.
——————————————————————————–
16. Previous Year Questions (PYQs)
- 1 Mark: What is the output of
len({1: "A", 2: "B", 1: "C"})? (Ans: 2, duplicate key overwrites). - 2 Marks: Differentiate between
pop()andpopitem(). (Ans:pop()needs a key;popitem()removes the last item and returns a tuple). - Assertion-Reason: Assertion:
d = {[1]: "A"}is valid. Reason: Keys must be immutable. (Ans: A is False, R is True).
——————————————————————————–
17. Practice MCQs
- Which is a valid key? A)
[1]B)(1, [2])C)(1, 2)D){1:2}.- Ans: C. Tuples are immutable ONLY if all elements are immutable.
- What does
dict.get('x', 5)return if ‘x’ is not present? A) Error B) None C) 5 D) 0.- Ans: C. It returns the default value provided.
- How is
popitem()different in Python 3.7+? A) Random removal B) LIFO removal C) FIFO removal D) Doesn’t exist.- Ans: B. It removes the last inserted item.
——————————————————————————–
18. Student FAQ
- Can a dictionary have a list as a value? Yes! Values can be anything—lists, tuples, or even other dictionaries.
- Is a dictionary a sequence? No. It is a Mapping. Sequences are ordered by position; mappings are linked by keys.
- How do I sort a dictionary by values? You can’t sort the dictionary itself in-place, but you can use
sorted(d.values())to get a sorted list of the values. - Why use
get()instead of[]?get()prevents your program from crashing with aKeyErrorif the key is missing. - Is
dicta keyword? No, it is a built-in type/constructor, but you should avoid using it as a variable name.
Keep coding and remember: in Python, the right “Key” opens every door!
