Skip to main content

Someone wanted to learn this too, so Grasp built them a personal learning path.

You can keep exploring this one or create your own

Storing and Retrieving Data with Python Lists and Dictionaries

Hello! In the previous lesson, you worked with individual numbers, strings, and booleans. A measurement such as 18.5 is useful on its own, but a machine-learning dataset contains many measurements, and each observation may have several named fields. This lesson introduces two ways to keep those values together: lists, which retrieve items by position, and dictionaries, which retrieve values by key.

Allow about 40 minutes to watch the selected video excerpts and run the examples in your notebook. You do not need to learn loops or conditional statements yet; for now, the goal is to store values and retrieve the ones you need.


Lists: retrieve by position

A list is an ordered collection. Write its elements between square brackets, separated by commas:

readings = [18.5, 20.0, 19.2]
print(readings)
print(len(readings))

The list has three elements. Python numbers their positions starting at zero, so readings[0] is 18.5, readings[1] is 20.0, and readings[2] is 19.2. The position is called an index.

Watch the list portion of Python Tutorial for Beginners 4: Lists, Tuples, and Sets by Corey Schafer. His examples use course names rather than measurements, but the same indexing rules apply to both.

Python Tutorial for Beginners 4: Lists, Tuples, and Sets

Watch Corey Schafer create a list and retrieve individual elements and slices. Then watch his short demonstration of adding an element.

Watch list retrieval, from the opening discussion of lists through the explanation of slicing. Focus on why the first index is 0 and why a slice stops before its ending index. Continue with adding an item, where append places a new element at the end; you can stop when he turns to insert.

Return to the notebook and retrieve values from readings:

print(readings[0])    # first: 18.5
print(readings[-1])   # last: 19.2
print(readings[:2])   # first two: [18.5, 20.0]

A negative index counts backward from the end, making -1 useful when you do not know a list’s length. A slice such as readings[:2] produces a new list containing elements up to, but not including, index 2. Asking for readings[3], by contrast, raises an IndexError: this three-element list has no element at index 3.

Lists can change after you create them. Assign to an existing index to replace its value, or use append to add a value at the end:

readings[1] = 21.0
readings.append(17.8)
print(readings)

The result is [18.5, 21.0, 19.2, 17.8]. Assignment changed the element at index 1; append increased the number of elements. You can also begin with an empty list, [], and add elements later.

A list can hold different types, but a list of comparable measurements is often easier to work with than one mixing numbers and text. Its defining feature is not that its elements must be numbers: it is that position matters.


Dictionaries: retrieve by key

Suppose 18.5 is one field in an observation, alongside a validity flag and a category label. Remembering that the reading is “element zero” and the flag is “element one” would be fragile. A dictionary lets you give each field a meaningful key:

observation = {
    "reading": 18.5,
    "valid": True,
    "category": "normal"
}

Each entry is a key–value pair. The key "reading" identifies the value 18.5; "valid" identifies True. The curly braces create the dictionary, while colons separate keys from values.

Watch the beginning of Python Tutorial for Beginners 5: Dictionaries – Working with Key-Value Pairs by Corey Schafer. His example represents one record with a dictionary and also shows that a value can itself be a list.

Python Tutorial for Beginners 5: Dictionaries - Working with Key-Value Pairs

Watch Corey Schafer introduce key–value pairs, create a dictionary, retrieve values, and add or update an entry.

Start with keys and creation, through printing the completed dictionary. In retrieving values, pay particular attention to the missing-key error and the alternative get method. Watch adding and updating, stopping after the direct-assignment example changes an existing value; the later update method is not needed here.

Retrieve a value by putting its key, not its position, in square brackets:

print(observation["reading"])   # 18.5
print(observation["valid"])     # True

Compare the meanings of the two bracket expressions you have seen:

Collection Example What goes in the brackets?
List readings[0] An integer position
Dictionary observation["reading"] A key

Keys must be unique within a dictionary. Several keys may have the same value, but assigning a second value to an existing key replaces the first; it does not create another entry with that key. For example:

observation["reading"] = 19.0
observation["unit"] = "degrees"
print(observation["reading"])
print(observation["unit"])

The first assignment updates an existing value; the second adds a new key–value pair. An empty dictionary is written {}.

Unlike list indices, dictionary keys do not mean “first item” or “second item.” Modern Python dictionaries preserve insertion order, but you retrieve their values by key rather than by numeric position.


When a key might be missing

observation["category"] works because "category" exists. If you try observation["source"] when that key is absent, Python raises a KeyError. This is useful when the field should exist: the error tells you that your expectation was wrong.

When a field is optional, get offers another choice:

print(observation.get("source"))             # None
print(observation.get("source", "unknown"))  # unknown

None is Python’s value for “no value.” You can supply a different fallback as the second argument to get. Be deliberate about that fallback: "unknown" is not an observed source; it is a value you chose to use when the key was missing.

The in operator checks for a key in a dictionary and produces a boolean, just like the comparisons you used last lesson:

print("reading" in observation)  # True
print("source" in observation)   # False

This differs from a list, where in checks whether a value occurs among its elements. Use a key lookup when you need the stored value, and use in when you need to know whether a key is present.


Putting the two structures together

A dataset can be represented as a list of observations, with each observation stored as a dictionary:

observations = [
    {"reading": 18.5, "valid": True},
    {"reading": 20.0, "valid": False},
    {"reading": 19.2, "valid": True}
]

print(observations[1])
print(observations[1]["reading"])

The first print displays the second dictionary. The second displays 20.0: observations[1] retrieves a record by position, and ["reading"] retrieves one field by key from that record. Read the expression one pair of brackets at a time.

This example is deliberately small enough to inspect in a notebook. Later, you will work with tabular-data tools designed for larger datasets, but the distinction will remain valuable: which observation do you want, and which field within it?


Takeaways

Use a list when you want an ordered collection whose elements you can retrieve by zero-based index. Use a dictionary when you want to associate values with meaningful, unique keys. Both can be changed after creation; both use square brackets for retrieval, but what belongs inside those brackets is different. For an optional dictionary key, get can return a fallback instead of raising a KeyError.

Next, you will use boolean expressions—including checks on values you retrieve here—to choose which code runs with conditional statements.

Can't find a good explanation? Sign up and we'll make it for you

Sign up