Datastructures - Dictionaries

Dictionaries expand upon the idea of sets. Much like a language dictionary that makes it easy to find definitions of words, in Python, dictionaries offer even broader applications.

A dictionary is a collection of unordered key-value pairs of elements, where keys are unique.

Just like with sets, dictionaries can be created with curly brackets, however if we add a colon into it, it will separate the left of the colon as the key and the right of it as the value; {key: value}. The key is the index of the dictionary which corresponds to a value. The dictionary may also be created with the built-in function dict.

  • dict01: demonstrates that we can use text as the key; when doing so, we must enclose it in quotation marks.
  • dict02: shows us dictionaries can have numbers as the keys, as well text or lists as the values.
  • dict03: illustrates one final crucial aspect of dictionaries: keys must be unique. If there are duplicate keys, the value of the last duplicate will be retained.

The key is the index for this data structure. In analogy to the list, the indices were 0, 1, 2, ..., and gave the associated element in the list. With the dictionary, the key is the index, and accessing it yields the value associated with this key.

The dictionary generalizes the list as we can define the indices however we would like. In the following code editor, the indices for dictionary dict01 are: 1, "two". And for the nested dictionary in the value of the "two" key, the index there is 3.

Practice Question

Given the dictionary below, which index path will lead to the Sugar Maple value that is within New England?

score: 0%


Great job on learning all of these definitions! Now that we've covered these fundamentals, as we move into learning functions in the next lesson, we can start combing them and applying them in more interesting ways to build our software development skills.