Create dictionaries with valid, unique keys.
ποΈ Dictionaries
Connect meaningful keys to values for fast lookup, record management, counting, grouping and structured real-world data.
student = {
"name": "Bhavya",
"score": 92
}
student["grade"] = "A"
print(student["name"])
print(student.get("grade"))
print(len(student))A
3
By the End of This Level
You will be able to organise and process keyβvalue data confidently.
Access, add, update and safely remove entries.
Iterate through keys, values and keyβvalue pairs.
Model nested records and solve counting problems.
Dictionary Fundamentals
A dictionary is a mutable mapping that associates each unique key with one value.
Dictionary literals use braces and colons: {"name": "Bhavya", "score": 92}. Python preserves insertion order, but dictionary access is based on keys rather than positions.
A data structure that retrieves a value using its key instead of a numeric sequence index.
{} or dict(){"name": "Venu"}{1: "One"}len({"a": 1}) β 1Keys must be unique and immutable/hashable, such as strings, numbers or tuples. Lists and dictionaries cannot be dictionary keys.
Accessing Dictionary Values
Square brackets require the key to exist. The get() method can return a safe default when the key is missing.
| Expression | Behaviour | Result |
|---|---|---|
student["name"] | Direct lookup | Value or KeyError |
student.get("name") | Safe lookup | Value or None |
student.get("grade", "NA") | Lookup with default | Value or "NA" |
"score" in student | Membership test | Checks keys |
Read Required and Optional Fields
student = {"name": "Bhavya", "score": 92}
print("Name =", student["name"])
print("City =", student.get("city", "Not given"))Name = Bhavya City = Not given
Adding, Updating and Removing Entries
Assignment adds a key when it is new and updates the associated value when the key already exists.
Update Inventory
stock = {"Pen": 10, "Book": 5}
stock["Book"] = 8
stock["Bag"] = 3
removed = stock.pop("Pen")
print(stock)
print("Removed =", removed){'Book': 8, 'Bag': 3}
Removed = 10Essential Dictionary Methods
| Method | Returns / performs | Typical use |
|---|---|---|
keys() | View of keys | Process labels or identifiers |
values() | View of values | Calculate totals or averages |
items() | Keyβvalue pairs | Unpack both during iteration |
get(key, default) | Safe value lookup | Avoid missing-key errors |
update(other) | Merges entries in place | Add or replace several entries |
pop(key) | Removed value | Delete and use an entry |
setdefault(key, value) | Existing or inserted value | Initialise grouping/counting data |
copy() | Shallow dictionary copy | Preserve the original mapping |
keys(), values() and items() produce views that reflect later changes to the dictionary.
Dictionary Iteration
Looping directly over a dictionary visits its keys. Use items() when the loop needs both keys and values.
Direct loop
for key in data:
print(key)Visits every key.
items()
for key, value in data.items():
print(key, value)Unpacks each pair clearly.
values()
for value in data.values():
print(value)Visits stored values only.
Display Subject Scores
scores = {"Python": 92, "SQL": 88}
for subject, score in scores.items():
print(subject, "=", score)Python = 92 SQL = 88
Nested Dictionaries
A dictionary value can itself be a dictionary, allowing related records to be organised hierarchically.
Store Multiple Students
students = {
101: {"name": "Bhavya", "score": 92},
102: {"name": "Venu", "score": 88}
}
print(students[101]["name"])
print(students[102]["score"])Bhavya 88
In students[101]["name"], first retrieve the record stored at key 101, then retrieve its "name" value.
Frequency Counting
A frequency dictionary uses each observed item as a key and its occurrence count as the value.
Count Characters
text = "banana"
frequency = {}
for character in text:
frequency[character] = frequency.get(character, 0) + 1
print(frequency){'b': 1, 'a': 3, 'n': 2}Common Dictionary Patterns
Fast Lookup
Map IDs, names or codes directly to associated information.
Counting
Map each observed value to its frequency.
Grouping
Map categories to lists of related values.
Record Modelling
Represent named fields without relying on numeric positions.
| Requirement | Suitable dictionary design |
|---|---|
| Find a student using roll number | {roll_number: student_record} |
| Count words | {word: frequency} |
| Group students by branch | {branch: [students]} |
| Store configuration | {setting: value} |
Common Dictionary Mistakes
data["city"]Direct access raises KeyError when the key is absent; use get() when absence is normal.
92 in studentThe in operator checks dictionary keys, not values.
{"a": 1, "a": 2}The later value replaces the earlier value for the same key.
del data[key]Do not change dictionary size while iterating over its live view; iterate over a copied list of keys when removal is required.
get() for optional data4. Inspect nested levels5. Verify update orderπ Dictionaries β Quick Revision
Review these rules before attempting the quiz and programming problems.
A dictionary stores keyβvalue pairs.
Keys are unique and must be hashable.
Dictionaries are mutable and preserve insertion order.
Square brackets raise KeyError for a missing key.
get() supports safe lookup and defaults.
Assignment adds a new key or updates an existing key.
items() provides keyβvalue pairs.
Direct dictionary iteration visits keys.
Nested dictionaries model structured records.
Frequency dictionaries map each item to its count.
π§ Level 8 Quiz
Choose one answer for each question.
1. Which symbol separates a dictionary key from its value?
2. Which statement about dictionary keys is correct?
3. What does data.get("x", 0) return when "x" is absent?
4. Which method provides keyβvalue pairs?
5. What does "name" in student check?
6. Which operation merges entries into the same dictionary?
π― 5 Programming Problems β Dictionaries
Follow the CodeBhavya pattern: understand the task, inspect the sample, use the editor, run, check, then compare with the official program.
A problem counts as Solved when its output passes before the official solution is opened.
Read a name and score, store them using meaningful keys and display both values.
Bhavya, 92Expected output: Name = Bhavya and Score = 92"name" and "score".Python Code Editor
Program Output
Run your program to see the output.
Test Case
student = {"name": input(), "score": int(input())}
print("Name =", student["name"])
print("Score =", student["score"])Read an existing item and its new quantity, then update and display the complete stock mapping.
Book, 8Expected output: Stock = {'Pen': 10, 'Book': 8}Python Code Editor
Program Output
Run your program to see the output.
Test Case
stock = {"Pen": 10, "Book": 5}
item = input()
quantity = int(input())
stock[item] = quantity
print("Stock =", stock)Read a product name and display its price, or Not found when it is absent.
PencilExpected output: Price = Not found"Not found" as the second argument to get().Python Code Editor
Program Output
Run your program to see the output.
Test Case
prices = {"Pen": 10, "Book": 50}
item = input()
print("Price =", prices.get(item, "Not found"))Read text and count every character using a frequency dictionary.
bananaExpected output: Frequency = {'b': 1, 'a': 3, 'n': 2}frequency.get(character, 0) + 1.Python Code Editor
Program Output
Run your program to see the output.
Test Case
text = input()
frequency = {}
for character in text:
frequency[character] = frequency.get(character, 0) + 1
print("Frequency =", frequency)Merge two subject-score dictionaries and display the resulting mapping.
{"Python": 90, "C": 85}Second: {"Java": 88, "SQL": 92}Expected output: Scores = {'Python': 90, 'C': 85, 'Java': 88, 'SQL': 92}update() on the first dictionary with the second dictionary.Python Code Editor
Program Output
Run your program to see the output.
Test Case
scores = {"Python": 90, "C": 85}
more_scores = {"Java": 88, "SQL": 92}
scores.update(more_scores)
print("Scores =", scores)π― Think in Keys and Values
Use a meaningful unique identifier.
Associate the required information.
Select brackets or get().
Iterate, count, group or merge.
π¬ Dictionary Mutation β Visual Flow
Watch one inventory dictionary change through lookup, update and insertion.
ποΈ How Dictionary Entries Change
1. Create the Original Mapping
The dictionary begins as {"Pen": 10} with one keyβvalue pair.
π Program Tracing β Frequency Counter
Trace the characters in aba and observe how the dictionary count changes.
Click Next to begin tracing.
β
π€ Dictionaries β Interview Questions
Answer aloud before opening each explanation.
What is the difference between bracket lookup and get()?
Bracket lookup raises KeyError when a key is absent. get() returns None or a supplied default instead.
What types can be dictionary keys?
Keys must be hashable, which normally means immutable values such as strings, numbers and tuples containing hashable elements.
How do keys(), values() and items() differ?
keys() provides keys, values() provides stored values and items() provides keyβvalue pairs suitable for unpacking.
What happens when a dictionary literal repeats a key?
The later value replaces the earlier value because one dictionary cannot contain the same key more than once.
What is the average time complexity of dictionary lookup?
Lookup, insertion and deletion are O(1) on average because dictionaries use a hash table.
When is a nested dictionary useful?
It is useful when each key identifies a structured record, such as mapping roll numbers to student dictionaries or departments to grouped data.
π‘ Dictionaries β Extra Tips
- 01
Use descriptive keys such as
"student_name"instead of unclear abbreviations. - 02
Use
get()when a missing key is an expected situation. - 03
Use
items()to avoid repeatedly looking up a value during iteration. - 04
Use
setdefault()carefully for grouping, or prefer clearer explicit logic while learning. - 05
Copy a dictionary before experimental updates when the original data must remain unchanged.
- 06
For predictable reports, sort keys before displaying them when insertion order is not meaningful.
βοΈ Dictionaries β Extra Practice Questions
- Count the frequency of every word in a sentence.
- Find the key associated with the highest numeric value.
- Invert a dictionary whose values are unique.
- Group student names by branch.
- Merge two dictionaries and add values for common keys.
- Remove all entries whose values are below a threshold.
- Build a dictionary mapping numbers from 1 to
nto their squares. - Check whether two dictionaries contain identical keyβvalue pairs.
- Create a nested dictionary for semester-wise subject marks.
- Find the first non-repeating character using frequency counting.
Dictionaries Complete
When you can design keys, choose safe lookup, iterate through entries and solve all five dictionary programs without help, mark this level complete and continue.
