course content

Course Content

Introduction to Python

What Is a Dictionary?What Is a Dictionary?

Throughout previous chapters, we have learned the data structures that can be indexed by numbers or a range of numbers. The next data structure we are going to learn can be indexed by key (which can be a string, tuple, number, etc.). This data type is called a dictionary. Values in dictionaries are represented as the pairs key:value. Let's take note of the aspects of a dictionary's keys.

  • You can use any immutable type as a dictionary's keys. Tuples can be used as keys only if they consist of strings, numbers, or tuples.
  • Keys are not repeated in the same dictionary.

To create a dictionary in Python, you need to put the pairs key:value between curly brackets.

For example, we can represent the countries' data as a dictionary. The keys in this dictionary will be the countries' names, and the respective values (area and population) will be stored as tuples.

Looks good! How do you access a specific element in a dictionary? As mentioned above, you can refer to the dictionary element by key, which is a string in our case (don't forget to use quotation marks). The key must be put between square brackets, like the index of a list or a tuple.

Section 4.

Chapter 10