PART 2 β€’ LEVEL 08

πŸ—‚οΈ Dictionaries

Connect meaningful keys to values for fast lookup, record management, counting, grouping and structured real-world data.

⏱ 95–110 minutesπŸ“š 8 conceptsπŸ’» 5 programs🧠 6-question quiz
student_record.pyPython 3
student = {
    "name": "Bhavya",
    "score": 92
}
student["grade"] = "A"

print(student["name"])
print(student.get("grade"))
print(len(student))
OUTPUTBhavya
A
3

By the End of This Level

You will be able to organise and process key–value data confidently.

01

Create dictionaries with valid, unique keys.

02

Access, add, update and safely remove entries.

03

Iterate through keys, values and key–value pairs.

04

Model nested records and solve counting problems.

01

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.

Mapping

A data structure that retrieves a value using its key instead of a numeric sequence index.

Empty dictionary{} or dict()
String keys{"name": "Venu"}
Numeric keys{1: "One"}
Lengthlen({"a": 1}) β†’ 1
Key rule

Keys must be unique and immutable/hashable, such as strings, numbers or tuples. Lists and dictionaries cannot be dictionary keys.

02

Accessing Dictionary Values

Square brackets require the key to exist. The get() method can return a safe default when the key is missing.

ExpressionBehaviourResult
student["name"]Direct lookupValue or KeyError
student.get("name")Safe lookupValue or None
student.get("grade", "NA")Lookup with defaultValue or "NA"
"score" in studentMembership testChecks keys
EXAMPLE 1

Read Required and Optional Fields

student = {"name": "Bhavya", "score": 92}
print("Name =", student["name"])
print("City =", student.get("city", "Not given"))
OUTPUT
Name = Bhavya
City = Not given
03

Adding, Updating and Removing Entries

Assignment adds a key when it is new and updates the associated value when the key already exists.

1Choose KeyMeaningful identifier
β†’
2Check EntryNew or existing
β†’
3Assign ValueAdd or replace
β†’
4Use MappingUpdated record
EXAMPLE 2

Update Inventory

stock = {"Pen": 10, "Book": 5}
stock["Book"] = 8
stock["Bag"] = 3
removed = stock.pop("Pen")
print(stock)
print("Removed =", removed)
OUTPUT
{'Book': 8, 'Bag': 3}
Removed = 10
04

Essential Dictionary Methods

MethodReturns / performsTypical use
keys()View of keysProcess labels or identifiers
values()View of valuesCalculate totals or averages
items()Key–value pairsUnpack both during iteration
get(key, default)Safe value lookupAvoid missing-key errors
update(other)Merges entries in placeAdd or replace several entries
pop(key)Removed valueDelete and use an entry
setdefault(key, value)Existing or inserted valueInitialise grouping/counting data
copy()Shallow dictionary copyPreserve the original mapping
Dynamic views

keys(), values() and items() produce views that reflect later changes to the dictionary.

05

Dictionary Iteration

Looping directly over a dictionary visits its keys. Use items() when the loop needs both keys and values.

KEYS

Direct loop

for key in data:
    print(key)

Visits every key.

VALUES

values()

for value in data.values():
    print(value)

Visits stored values only.

EXAMPLE 3

Display Subject Scores

scores = {"Python": 92, "SQL": 88}
for subject, score in scores.items():
    print(subject, "=", score)
OUTPUT
Python = 92
SQL = 88
06

Nested Dictionaries

A dictionary value can itself be a dictionary, allowing related records to be organised hierarchically.

EXAMPLE 4

Store Multiple Students

students = {
    101: {"name": "Bhavya", "score": 92},
    102: {"name": "Venu", "score": 88}
}
print(students[101]["name"])
print(students[102]["score"])
OUTPUT
Bhavya
88
Read from outside to inside

In students[101]["name"], first retrieve the record stored at key 101, then retrieve its "name" value.

07

Frequency Counting

A frequency dictionary uses each observed item as a key and its occurrence count as the value.

EXAMPLE 5

Count Characters

text = "banana"
frequency = {}

for character in text:
    frequency[character] = frequency.get(character, 0) + 1

print(frequency)
OUTPUT
{'b': 1, 'a': 3, 'n': 2}
08

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.

RequirementSuitable 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

Missing Key
data["city"]

Direct access raises KeyError when the key is absent; use get() when absence is normal.

Membership
92 in student

The in operator checks dictionary keys, not values.

Duplicate Key
{"a": 1, "a": 2}

The later value replaces the earlier value for the same key.

Changing Size
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.

Debug mappings:1. Print available keys2. Confirm exact key type3. Use get() for optional data4. Inspect nested levels5. Verify update order
QUICK REVISION

πŸ“Œ Dictionaries β€” Quick Revision

Review these rules before attempting the quiz and programming problems.

01

A dictionary stores key–value pairs.

02

Keys are unique and must be hashable.

03

Dictionaries are mutable and preserve insertion order.

04

Square brackets raise KeyError for a missing key.

05

get() supports safe lookup and defaults.

06

Assignment adds a new key or updates an existing key.

07

items() provides key–value pairs.

08

Direct dictionary iteration visits keys.

09

Nested dictionaries model structured records.

10

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?

PRACTICE

🎯 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.

πŸ“ˆ Dictionaries Practice Progress
Solved0 / 5
Completed with Solution0
Total Score0 / 500
Completion0%

A problem counts as Solved when its output passes before the official solution is opened.

1. Create a Student Record

Read a name and score, store them using meaningful keys and display both values.

Sample input: Bhavya, 92Expected output: Name = Bhavya and Score = 92
2. Update Inventory

Read an existing item and its new quantity, then update and display the complete stock mapping.

Sample input: Book, 8Expected output: Stock = {'Pen': 10, 'Book': 8}
3. Safe Product Lookup

Read a product name and display its price, or Not found when it is absent.

Sample input: PencilExpected output: Price = Not found
4. Character Frequency

Read text and count every character using a frequency dictionary.

Sample input: bananaExpected output: Frequency = {'b': 1, 'a': 3, 'n': 2}
5. Merge Subject Scores

Merge two subject-score dictionaries and display the resulting mapping.

First: {"Python": 90, "C": 85}Second: {"Java": 88, "SQL": 92}Expected output: Scores = {'Python': 90, 'C': 85, 'Java': 88, 'SQL': 92}
KEY TAKEAWAY

🎯 Think in Keys and Values

1Choose Key

Use a meaningful unique identifier.

β†’
2Store Value

Associate the required information.

β†’
3Retrieve Safely

Select brackets or get().

β†’
4Process Entries

Iterate, count, group or merge.

Dictionaries make programs clearer when values have meaningful labels: design reliable keys, use safe lookup where appropriate and select iteration views deliberately.

INTERACTIVE LEARNING

🎬 Dictionary Mutation β€” Visual Flow

Watch one inventory dictionary change through lookup, update and insertion.

PROGRAM TRACING

πŸ”Ž Program Tracing β€” Frequency Counter

Trace the characters in aba and observe how the dictionary count changes.

INTERVIEW PREPARATION

🎀 Dictionaries β€” Interview Questions

Answer aloud before opening each explanation.

1.

What is the difference between bracket lookup and get()?

2.

What types can be dictionary keys?

3.

How do keys(), values() and items() differ?

4.

What happens when a dictionary literal repeats a key?

5.

What is the average time complexity of dictionary lookup?

6.

When is a nested dictionary useful?

EXTRA TIPS

πŸ’‘ 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.

EXTRA PRACTICE

✍️ Dictionaries β€” Extra Practice Questions

  1. Count the frequency of every word in a sentence.
  2. Find the key associated with the highest numeric value.
  3. Invert a dictionary whose values are unique.
  4. Group student names by branch.
  5. Merge two dictionaries and add values for common keys.
  6. Remove all entries whose values are below a threshold.
  7. Build a dictionary mapping numbers from 1 to n to their squares.
  8. Check whether two dictionaries contain identical key–value pairs.
  9. Create a nested dictionary for semester-wise subject marks.
  10. 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.