Dictionary Keys and Data Types
In our previous lesson, we primarily used strings as keys (e.g., 'name', 'a', 'b'). However, Python dictionaries are much more flexible than that. While keys must be of a data type that is "immutable" (meaning it cannot change), you aren't restricted to just words.
Using Numbers as Keys
You can use integers or even floats as dictionary keys. This is useful when the "label" for your data is naturally a number, but you still want the properties of a dictionary rather than the indexed order of a list.
- Print the dictionary with the integer key.
- Change one of the keys to True, and print the dictionary.
- Now try changing one of the keys to a list, new_dict = {[100] : 'balloons', 'color' : 'red'}. print(new_dict[[100]])
- print the color key in this new dictionary; new_dict = {'99' : 'balloons', 'color' : 'red', 'color' : 'blue'}
Key Rules to Remember
- Immutability: Keys must be a data type that cannot be changed (Strings, Integers, and Tuples are common keys). You cannot use a list as a key because lists can be modified.
- Uniqueness: Every key in a dictionary must be unique. If you try to use the same key twice, the second one will simply overwrite the first.
Why use an Integer key instead of a List index?
It might look like new_dict[99] is the same as accessing a list at index 99, but it is very different:
- In a list: To have an item at index 99, you must have 98 other items before it.
- In a dictionary: You can have a single item with the key 99 without needing any other data. It is a label, not a position.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named dictionary_keys.py in your part29 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: Integer Keys
Practice using whole numbers as identifiers instead of strings.
-
Task: Create a dictionary called
priceswhere the key is the item ID (an integer) and the value is the price (a float). - Goal: Print the price by targeting the key.
Exercise 2: Mixed Key Types
Dictionaries can handle a variety of immutable types at once.
-
Starting Code:
user_data = {1: "Admin", "status": "Active", 2.5: "Version"} -
Task: Access and print the value associated with
the float key
2.5. - Goal: Prove that decimals (floats) can also function as keys.
Exercise 3: The Uniqueness Rule
See what happens when you try to reuse a key.
-
Task: Create a dictionary:
points = {"team_a": 10, "team_a": 20}. -
Goal: Print
points["team_a"]and observe which value remains.
Exercise 4: The "List as Key" Error
Identify what types are not allowed as keys.
-
Task: Try to create this dictionary:
bad_dict = {[1, 2]: "numbers"}. -
Goal: Run the code and identify the error (it
should be a
TypeError: unhashable type: 'list').
Exercise 5: Real-world Mapping
Use integers as keys for a simple ID system.
-
Task: Create a dictionary
employeeswhere the keys are employee IDs (1001, 1002) and the values are their names ("Sarah", "John"). -
Goal: Print a sentence:
"Employee 1001 is " + employees[1001].
Don't Forget to commit and Push!