Loading notes...
Loading notes...
Class 11 • Chapter 10
Chapter 10 covers Dictionaries, Python's powerful Key-Value data structure. It explains how to map labels to data, preventing KeyErrors, and utilizing dictionary-specific methods.
Lists and Tuples are accessed using integer indices (0, 1, 2). This is great for sequences, but terrible if you want to look up data based on a label (e.g., finding the grade of 'Basant' without knowing his exact position in the list). Dictionaries solve this problem. A Dictionary is an unordered, mutable collection of Key-Value pairs. It acts like a real-world dictionary: you look up a word (the Key) to find its definition (the Value).
10.1 Creating Dictionaries
Dictionaries are enclosed in curly braces `{}`. Each item consists of a Key and a Value separated by a colon `:`. Items are separated by commas. Keys MUST be unique and Immutable (like Strings, Integers, or Tuples). Values can be anything (including Lists or other Dictionaries).
# Creating a dictionary
student_grades = {
"Basant": 95,
"Alice": 88,
"Bob": 72
}
# Creating an empty dictionary
empty_dict = {}10.2 Accessing and Modifying Data
You access a value not by its index number, but by providing its Key inside square brackets. Because dictionaries are Mutable, you can easily add new Key-Value pairs or update existing ones.
inventory = {"Apples": 10, "Bananas": 5}
# Accessing a value
print(inventory["Apples"]) # Output: 10
# Adding a new Key-Value pair
inventory["Oranges"] = 20
# Updating an existing value
inventory["Bananas"] = 8
print(inventory) # Output: {'Apples': 10, 'Bananas': 8, 'Oranges': 20}10.3 The get() Method
If you try to access a key that does not exist using `dict['key']`, Python will instantly crash with a KeyError. To safely retrieve data, use the `.get(key)` method. If the key is missing, it returns `None` (or a default value) instead of crashing.
user = {"name": "John", "age": 30}
# print(user["email"]) <-- CRASH! KeyError
print(user.get("email")) # Output: None
print(user.get("email", "Not Provided")) # Output: Not Provided10.4 Dictionary Methods
10.5 Traversing a Dictionary
You can loop through a dictionary in several ways depending on whether you need the keys, the values, or both.
scores = {"Math": 90, "Science": 85}
# Looping through keys (Default behavior)
for subject in scores:
print(subject)
# Looping through both Keys and Values using .items()
for subject, mark in scores.items():
print(f"Got {mark} in {subject}")