Chapter 5: Dictionaries and Structuring Data

The “Parallel List” Nightmare

Scene: The Computer Lab. Chaitanya has two massive lists written on the whiteboard.

Chaitanya: Ma’am, looking up student phone numbers is becoming a nightmare.

  • List 1: names = ['Alice', 'Bob', 'Chaitanya', ...]
  • List 2: numbers = ['1234', '5678', '9999', ...]

Chaitanya: If I want Chaitanya’s number, I have to:

  1. Loop through names to find ‘Chaitanya’.
  2. Get the index (let’s say it’s 2).
  3. Go to numbers and get the value at index 2. It’s slow, and if I accidentally sort one list but not the other, the data gets mismatched! Alice ends up with Bob’s phone number.

Aditi Ma’am: That is because you are using the wrong tool. You are treating data like a Queue (List) when you should be treating it like an Address Book.

Chaitanya: An address book?

Aditi Ma’am: In an address book, you don’t say “Give me the 5th person on page 10.” You say, “Give me Chaitanya.” You look up data using a Key (the name), not an Index (the position). In Python, we call this a Dictionary.

The Dictionary Data Type

Aditi Ma’am: A list uses square brackets []. A dictionary uses curly braces {}.

Python

my_cat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'}

Aditi Ma’am: But let’s make it relevant. Let’s create a dictionary for a student.

Python

student = {'name': 'Chaitanya', 'age': 15, 'house': 'Red'}

Chaitanya: So 'name', 'age', and 'house' are the Keys?

Aditi Ma’am: Yes. And 'Chaitanya', 15, and 'Red' are the Values. To get data out, you use the key.

Python

>>> student['name']
'Chaitanya'
>>> 'Student ' + student['name'] + ' is in ' + student['house'] + ' House.'
'Student Chaitanya is in Red House.'

Chaitanya: This is so much faster! I don’t need to know where the data is, just what it is labeled.

Dictionaries vs. Lists (The Order Myth)

Aditi Ma’am: Here is the biggest difference.

  • Lists are Ordered: ['a', 'b'] is NOT the same as ['b', 'a'].
  • Dictionaries are Unordered: The order doesn’t matter.

Python

>>> list1 = ['cats', 'dogs']
>>> list2 = ['dogs', 'cats']
>>> list1 == list2
False  # Order matters!

>>> dict1 = {'name': 'Zophie', 'species': 'cat'}
>>> dict2 = {'species': 'cat', 'name': 'Zophie'}
>>> dict1 == dict2
True   # Order does NOT matter!

Aditi Ma’am: Because dictionaries are unordered, you cannot slice them. You cannot ask for student[0]. It will crash with a KeyError because there is no key named 0.

The keys(), values(), and items() Methods

Chaitanya: What if I want to print a list of all the keys? Just to see what data we have?

Aditi Ma’am: You use the dictionary methods.

  1. values(): Returns just the values.
  2. keys(): Returns just the keys.
  3. items(): Returns both as tuples.

Chaitanya: Let me try looping through them.

Python

student = {'name': 'Chaitanya', 'age': 15, 'house': 'Red'}

print('--- VALUES ---')
for v in student.values():
    print(v)

print('--- KEYS ---')
for k in student.keys():
    print(k)

print('--- ITEMS ---')
for k, v in student.items():
    print('Key: ' + k + ' Value: ' + str(v))

Output:

--- VALUES ---
Chaitanya
15
Red
--- KEYS ---
name
age
house
--- ITEMS ---
Key: name Value: Chaitanya
Key: age Value: 15
Key: house Value: Red

Aditi Ma’am: This items() method is your best friend when building reports. You get the label and the data in one shot.

Checking Existence (in and not in)

Chaitanya: What if I try to access a key that doesn’t exist? Like student['grade']?

Aditi Ma’am: It will crash. KeyError. To prevent this, check if the key exists first.

Python

'name' in student  # True
'grade' in student # False

The get() Method (The Safety Net)

Aditi Ma’am: Checking with if 'key' in dict every single time is tedious. Python has a shortcut called get(). Syntax: dictionary.get(key, default_value)

Chaitanya: “Default value”?

Aditi Ma’am: It’s the backup plan. “Try to get this key. If it doesn’t exist, give me this value instead of crashing.”

Python

picnic_items = {'apples': 5, 'cups': 2}

print('I am bringing ' + str(picnic_items.get('cups', 0)) + ' cups.')
print('I am bringing ' + str(picnic_items.get('eggs', 0)) + ' eggs.')

Output:

I am bringing 2 cups.
I am bringing 0 eggs.

Chaitanya: It didn’t crash on ‘eggs’! It just gave me 0.

Aditi Ma’am: Exactly. It’s safer and cleaner.

The setdefault() Method (The Lazy Initialization)

Aditi Ma’am: Imagine you are counting votes for the Student Council. You pick up a ballot.

  1. Check if the candidate is already in the dictionary.
  2. If not, add them with 0 votes.
  3. Then add 1 to their count.

Chaitanya: That sounds like an if statement.

Python

if 'Rahul' not in votes:
    votes['Rahul'] = 0
votes['Rahul'] += 1

Aditi Ma’am: We can do that in one line with setdefault(). “Set this key to this value only if it doesn’t exist yet.”

Python

votes = {'Rahul': 1}
votes.setdefault('Rahul', 0) # Does nothing, Rahul is already there.
votes.setdefault('Simran', 0) # Adds Simran with 0.

Project: Character Count (The Letter Analysis)

Aditi Ma’am: Let’s use setdefault() to solve a real problem. I want you to count how many times every letter appears in this sentence: “It was a bright cold day in April, and the clocks were striking thirteen.”

Chaitanya: I’d need 26 variables? count_a, count_b…?

Aditi Ma’am: No! Use a dictionary. The Keys will be the letters, and the Values will be the counts.

Python

message = 'It was a bright cold day in April, and the clocks were striking thirteen.'
count = {}

for character in message:
    count.setdefault(character, 0) # Ensure the key exists
    count[character] = count[character] + 1

print(count)

Output: {'I': 1, 't': 6, ' ': 13, 'w': 2, 'a': 4, ...}

Chaitanya: That was incredibly fast. It handled spaces, commas, and capital letters automatically.

Pretty Printing (pprint)

Chaitanya: The output is ugly though. It’s all one long line.

Aditi Ma’am: Import the pprint module. It stands for “Pretty Print.”

Python

import pprint
pprint.pprint(count)

Output:

{' ': 13,
 ',' : 1,
 'I': 1,
 'a': 4,
 ...}

Aditi Ma’am: It sorts the keys and stacks them neatly. Much easier to read.

Nested Dictionaries (The School Database)

Aditi Ma’am: Now, Chaitanya, you are ready for the final boss. A real database isn’t just a list of names. It’s a structure.

  • A Dictionary of Students.
  • Each Student is a Dictionary of Details.

Python

all_students = {
    'Chaitanya': {'age': 15, 'grades': {'Math': 90, 'Science': 85}},
    'Rahul':     {'age': 16, 'grades': {'Math': 55, 'Science': 70}},
}

Chaitanya: That looks complex. How do I get Rahul’s Math grade?

Aditi Ma’am: You drill down.

  1. all_students['Rahul'] gives you Rahul’s dictionary.
  2. ['grades'] gives you the grades dictionary.
  3. ['Math'] gives you the number.

Python

print(all_students['Rahul']['grades']['Math'])

Output: 55

Aditi Ma’am: This is how JSON works. This is how web APIs work. By mastering Nested Dictionaries, you can model anything—from a School System to a Tic-Tac-Toe board.

Summary Box

  • Dictionaries {}: Unordered Key-Value pairs.
  • Access: dict['key'].
  • Methods: keys(), values(), items().
  • get(key, default): Safe retrieval.
  • setdefault(key, val): Set only if missing.
  • pprint: Make it readable.

Aditi’s Pro-Tip: “If you need an ordered list, use a List. If you need to label your data so you can find it later without searching, use a Dictionary.”

Leave a Comment

💬 Join Telegram