Free Study Material
Lists and tuples locate a value by its numeric position. A dictionary locates a value by a name you choose yourself — a far more natural fit for data like a student's marks in different subjects.
A dictionary stores data as key-value pairs, written inside curly braces {}. Each key maps to exactly one value, and every key must be unique. A dictionary is mutable.
student = {"name": "Aisha", "marks": 91}
Keys must be an immutable type — commonly a string or number. Values can be anything.
marks = {"Physics": 85, "Chemistry": 78, "Maths": 92}
print(marks)
print(type(marks))
print(marks["Physics"])
marks maps each subject (the key) to a score (the value). type(marks) prints <class 'dict'>. marks["Physics"] reaches the value paired with "Physics", giving 85 — by key name, not by numeric position.
Note:{}on its own creates an empty dictionary, even though sets also use curly braces — Python always treats bare{}as a dictionary.
A dictionary is the right structure specifically when data is naturally described by a label rather than a position — marks["Physics"] is more direct than needing to remember Physics happens to sit at some index of a separate list.
A dictionary stores key-value pairs in curly braces {}, with every key unique and immutable, and values of any type. A value is reached by its key (my_dict["key"]), not by numeric position.
A Dictionary is an unordered collection of items where each item consists of a Key and a Value. It is enclosed in Curly Braces { }.
# 1. Empty Dictionary
empty = {}
# 2. Student Record (Strings as Keys)
student = {
"Name": "Rahul",
"Age": 16,
"Stream": "CS"
}
print("Student Data:", student)
# 3. Number Mapping (Integers as Keys)
rankings = {
1: "Gold",
2: "Silver",
3: "Bronze"
}
print("Rank 1 Prize:", rankings[1])
# Rule 1: Duplicate Keys overwrite previous ones
data = {
"Score": 100,
"Score": 95 # This overwrites 100!
}
print("Duplicate Test:", data)
# Output: {'Score': 95}
# Rule 2: Mutable Keys are Forbidden
# Uncommenting the next line causes an Error
# invalid = { ["A", "B"] : "List Key" }
# TypeError: unhashable type: 'list'
This topic covers reading a value safely, adding a new pair, and changing an existing one — the everyday operations a dictionary is used for.
key. Raises KeyError if key doesn't exist.key, or None if it doesn't exist.key doesn't exist, or overwrites it if it does.marks = {"Physics": 85, "Chemistry": 78}
print(marks.get("Maths"))
marks["Maths"] = 92
marks["Physics"] = 90
print(marks)
marks.get("Maths") returns None, since "Maths" isn't a key yet — no error. marks["Maths"] = 92 adds a brand-new pair. marks["Physics"] = 90 overwrites the existing value, since that key already exists. Final result: {'Physics': 90, 'Chemistry': 78, 'Maths': 92}.
Warning:marks["Maths"](using[ ]) on a dictionary that doesn't yet have that key raisesKeyError: 'Maths'— use.get()whenever a key's absence is a normal possibility.
Whether my_dict[key] = value adds or overwrites depends only on whether key was already present — the same one line handles both cases, unlike a list, which needs separate operations for adding versus updating.
my_dict[key] reads a value and raises KeyError if missing; my_dict.get(key) reads a value and returns None instead. my_dict[key] = value both adds and overwrites, depending only on whether the key already existed.
⚠️ Crashes (KeyError) if key not found.
✅ Returns 'None' if key not found.
user = {
"username": "coder123",
"level": 5
}
# 1. Successful Access
print("User:", user["username"]) # Output: coder123
# 2. The Danger of Brackets
# print(user["score"]) <-- ERROR! KeyError: 'score'
# 3. The Safety of .get()
print("Score:", user.get("score")) # Output: None
print("Level:", user.get("level")) # Output: 5
prices = {"Apple": 100, "Banana": 40}
print("Original:", prices)
# Case A: Modifying (Key 'Apple' exists)
prices["Apple"] = 120
print("After Update:", prices)
# Result: Apple is now 120
# Case B: Adding (Key 'Mango' does not exist)
prices["Mango"] = 80
print("After Add:", prices)
# Result: Mango is added to the end
# Deleting a key
del prices["Banana"]
print("After Delete:", prices)
# Result: Banana is gone. Warning: Crashes if key isn't there!
Beyond reading one key at a time, a dictionary has built-in methods for supplying a fallback value, merging in many pairs at once, and pulling out its keys, values, or pairs together.
default instead of None when key is missing.marks = {"Physics": 85, "Chemistry": 78}
print(marks.get("Maths", 0))
marks.update({"Maths": 92, "Physics": 88})
print(marks)
print(list(marks.keys()))
print(list(marks.values()))
print(list(marks.items()))
marks.get("Maths", 0) returns the fallback 0, since "Maths" isn't a key; marks itself is unchanged by get(). marks.update({"Maths": 92, "Physics": 88}) adds "Maths" and overwrites "Physics" in one call: {'Physics': 88, 'Chemistry': 78, 'Maths': 92}. list(marks.keys()) gives ['Physics', 'Chemistry', 'Maths']; list(marks.values()) gives [88, 78, 92]; list(marks.items()) gives [('Physics', 88), ('Chemistry', 78), ('Maths', 92)].
Note:keys(),values(), anditems()return live view objects, not plain lists — wrapping them inlist(), as above, takes a fixed snapshot.
update() is the dictionary equivalent of a list's extend() — both merge one collection's contents into another in a single call, rather than one line per pair.
get(key, default) returns a fallback without changing the dictionary; update(other_dict) merges another dictionary's pairs in; keys(), values(), items() return live views of a dictionary's keys, values, or pairs.
Built-in functions are pre-defined in Python. Unlike methods, these functions take the Dictionary Object as an argument inside parentheses. They are primarily used for creating dictionaries and measuring their size.
# Rule: dict() creates a dictionary from a list of tuples or keyword arguments
data = dict([("City", "Delhi"), ("Temp", 25)])
print("Created Dictionary:", data)
# Output: {'City': 'Delhi', 'Temp': 25}
# You can also use keyword arguments
scores = dict(Math=95, IP=98)
print("Scores:", scores)
# Output: {'Math': 95, 'IP': 98}
# Rule: len() counts the number of pairs, not individual elements
student = {"Name": "Amit", "Roll": 1, "Stream": "IP"}
print("Total Pairs:", len(student))
# Output: 3
# Rule: del can delete a specific key using its name
stock = {"Apples": 50, "Bananas": 20}
del stock["Bananas"]
print("After Deletion:", stock)
# Output: {'Apples': 50}
# Rule: del stock (without brackets) deletes the whole variable from memory
This closing topic covers looping through a dictionary's contents, and the methods that remove data from one.
for key in my_dict: visits every key; for key, value in my_dict.items(): visits both together.key and returns its value.key, returns nothing.marks = {"Physics": 85, "Chemistry": 78, "Maths": 92}
for subject, score in marks.items():
print(subject, "scored", score)
removed = marks.pop("Chemistry")
print(removed, marks, len(marks))
The loop unpacks marks.items() directly into subject and score, printing each pair. marks.pop("Chemistry") removes that pair and returns 78; marks becomes {'Physics': 85, 'Maths': 92}, and len(marks) is 2.
Note: Looping directly over a dictionary (for key in my_dict:) visits keys only, never values — exactly why.items()exists for whenever both are needed together.
pop(key) on a dictionary mirrors pop(index) on a list — both remove by identifying a specific location and hand back what was removed.
for key, value in my_dict.items(): traverses both together. pop(key) removes by key and returns the value; popitem() removes the most recently added pair; del my_dict[key] removes without returning anything; clear() empties the dictionary; len() counts its pairs.
In IP, we often need to separate the "labels" (keys) from the "data" (values). Python provides three primary methods to view different parts of a dictionary without changing them.
These methods return view objects. This means if the dictionary changes, the view object updates automatically. They are essential for looping through data.
# Rule: .keys() returns only the labels, .values() returns only the data
inventory = {"Keyboard": 15, "Mouse": 22, "Monitor": 8}
print("Labels (Keys):", inventory.keys())
# Output: dict_keys(['Keyboard', 'Mouse', 'Monitor'])
print("Data (Values):", inventory.values())
# Output: dict_values([15, 22, 8])
# Rule: .items() returns pairs as tuples, perfect for 'for' loops
sales = {"Jan": 5000, "Feb": 4500}
print("All Pairs:", sales.items())
# Output: dict_items([('Jan', 5000), ('Feb', 4500)])
To keep our data up to date, we use update() to add new information and clear() to reset our data collection.
# Rule: .update() merges a new dictionary into the current one
# Existing keys are overwritten, new keys are added
emp = {"Name": "Rahul", "Dept": "Sales"}
new_info = {"Dept": "IT", "Salary": 45000}
emp.update(new_info)
print("Updated Record:", emp)
# Output: {'Name': 'Rahul', 'Dept': 'IT', 'Salary': 45000}
# Rule: .clear() removes all items but the variable name still exists
temp_data = {"Mon": 32, "Tue": 34}
temp_data.clear()
print("After Clear:", temp_data)
# Output: {}