Flat_Eric working on his P.C.

Dictionary Keys

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.

Key Rules to Remember

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:

  1. In a list: To have an item at index 99, you must have 98 other items before it.
  2. 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:

Exercise 1: Integer Keys

Practice using whole numbers as identifiers instead of strings.

Exercise 2: Mixed Key Types

Dictionaries can handle a variety of immutable types at once.

Exercise 3: The Uniqueness Rule

See what happens when you try to reuse a key.

Exercise 4: The "List as Key" Error

Identify what types are not allowed as keys.

Exercise 5: Real-world Mapping

Use integers as keys for a simple ID system.

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course