Skip to content

Suggestion: Clarify dictionary access with square brackets #1360

Description

@NathanLovato

A student was confused by this line in L25

var item_count = inventory[item_name]

They expected the square brackets to "return" the dictionary key's position in the list of keys, sort of similarly to how you access values in an array by index. The lesson and perhaps previous lessons don't make the distinction between array indexes and dictionary keys explicit enough.

The Lesson 25 practice also did not clearly explain how this modifies the inventory:

inventory[item_name] += amount

Things we could improve:

  • Review lessons probably 24 and 25 to clarify that [] is an access operator and it works differently depending on the context.
  • Explain that arrays use an int index, while dictionaries use a key to look up a value. We should probably say that dictionaries themselves do not have positional indexes (NB: unless you call a function to get an array of keys or values, but that's not the dictionary anymore).
  • Make sure we clearly explain and show that, in a loop over a dict, the loop variable contains one key at a time, and that using the brackets finds the value associated with that key. A visualization would help there and also mini exercises embedded in the lesson.

Related: #1217

Metadata

Metadata

Assignees

No one assigned

    Labels

    contentIssues with the lessons, practices, including their code examples

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions