Dictionaries
The next data structure we will learn is the Dictionary. In other programming languages, you might hear this referred to as an Object or a Map, but in Python, it is called a dict.
If you type dict into a .py file, you will notice the color change (usually to green) because it is a built-in data type. If you hover your mouse over it, your code editor will show you its purpose: dict(mapping) --> (key, value) pairs.
Organizing Data
Dictionaries are a powerful way to organize data. With Lists, we learned that data is ordered by position, and we access it using an index (0, 1, 2...).
Dictionaries work differently. Instead of an index, they use Key-Value pairs.
Syntax
The syntax for a dictionary uses curly braces {}. Inside the braces, you define a key, followed by a colon :, and then the value. Each pair is separated by a comma.
Accessing Data in a Dictionary
To access the data inside a dictionary, we target the key to retrieve its corresponding value.
For example, given the dictionary: my_dict = {'one': 1, 'two': 2, 'chicken': 3}, To access the value associated with 'one', we use square brackets with the key name inside:
- Print each of the keys to get the value.
- Print a key that doesn't exist; 'three'.
When you try to access or print a key that doesn't exist, Python will trigger an error—specifically a KeyError. For example, if you have a dictionary with numbers up to two and try to call my_dict['three'], Python will stop the program and tell you KeyError: 'three'.
Think of the key as the "address" and the value as the "person" living there. If you provide the correct address, Python gives you back the person!
Memory and Order
A dictionary in Python is an unordered collection of key-value pairs.
- Lists are stored sequentially in memory, meaning they have a specific order that allows you to access them by an index (position).
- Dictionaries do not store items in a linear order in memory. Because of this "unordered" nature, you cannot use an index like my_dict[0] to get the first item. You must access the data using the unique key you assigned to it.
Think of a list like a row of houses on a street where you can say "go to the 3rd house." A dictionary is more like a scattered group of houses where you have to say "go to the 'Blue' house" to find what you need.
Data
One of the most powerful features of dictionaries (and lists) is their flexibility. You can store any data type as a value—integers, strings, booleans, or even other lists!
For example:
my_dict = {'a' : [1, 2, 3], 'b' : 'Karen', 'c' : True}
Accessing Nested Data
To get to data hidden inside a list that is inside a dictionary, you simply "chain" your requests. First, you target the key to get the list, then you use an index to get the specific number.
- Print the entire dictionary
- Print values for keys a, b, and c
- Print the number 2 from the value of key 'a'
- Print the 'r' in the value of key 'b'
Nested Structures
Things get really interesting when we combine these structures. You can nest a dictionary inside a list, creating a list of dictionaries. This is a very common way to store multiple records, like a list of users or products.
For example:
this_list = [
{'a' : [1, 2, 3], 'b' : 'Karen', 'c' : True},
{'a' : [4, 5, 6], 'b' : 'Kieran', 'c' : False}
]
Deep Diving into Data
To pull a specific value out of this structure, you follow the path from the outside in. If you want the number 2 from the first dictionary:
- this_list[0]: Targets the first item in the list (the first dictionary).
- ['a']: Targets the key 'a' inside that dictionary.
- [1]: Targets the second item (index 1) in the list assigned to that key.
Try it out:
- Grab number 2 from the first dict key a.
- Grab the 'a' from 'Kieran'.
Choosing Between Lists and Dictionaries
A common question for new programmers is: "When do I use a list, and when do I use a dictionary?" The choice depends entirely on how you need to access and think about your data.
Use a List when Order Matters
Lists are ordered. This makes them perfect for sequences where the position defines the data.
- Example: A queue of people waiting in line.
- Why: You need to know who is 1st, 2nd, and 3rd. If someone leaves the line, everyone else moves up a spot. The index is the most important way to track them.
Use a Dictionary when Labels Matter
Dictionaries are unordered and map-based. They are ideal when you have a specific "entity" (like a student or a product) with different attributes.
- Example: A student profile for the Python Essentials course.
- Data needed: Name, parts finished, pre-test score, and post-test score.
- Why: You don't care if the "name" is stored "before" the "score" in memory. You just want to be able to say, "Give me the student's score," and get that specific piece of data instantly using a label.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named dictionary.py in your part28 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: The Basic Dictionary
Practice creating a simple dictionary to store a student's basic information.
-
Task: Create a dictionary named
studentwith three keys:"name"(set to "Alex"),"age"(set to 18), and"major"(set to "Coding"). -
Goal: Print the value associated with the
"major"key.
Exercise 2: The Key Error Trap
Understanding what happens when you look for a label that isn't there.
-
Starting Dictionary:
inventory = {'apples': 10, 'bananas': 5} -
Task: Try to print
inventory['pears']. - Goal: Observe the error message in your console and identify the specific error name (e.g., KeyError).
Exercise 3: List Inside a Dict
Dictionaries can hold complex data like lists.
-
Starting Dictionary:
vault = {'passwords': [1234, 5678, 9012], 'owner': 'Admin'} -
Task: Access the list under the key
'passwords'and print only the second password (5678). -
Goal: Use the "chaining" method:
vault[key][index].
Exercise 4: Dict Inside a List
This is the standard way data is often structured in the real world.
-
Starting List:
users = [{'id': 1, 'active': True}, {'id': 2, 'active': False}] -
Task: Access the second dictionary in the list and
print its
'active'status. - Goal: Correctly chain the list index and the dictionary key.
Exercise 5: The Ultimate Deep Dive
Let's combine everything you've learned about nesting.
-
Starting List:
data = [{'scores': [80, 90, 100]}, {'scores': [70, 85, 95]}] -
Task: Retrieve the score
100from the first dictionary. -
Goal: Successfully chain
data[index]['key'][index].
Don't Forget to commit and Push!