12Dictionaries

Python is a great choice of languages to use when working with sets of data! You previously learned how to create a list to store items, each of which consists of a singular object. But sometimes, named values may be more appropriate for the data you're using. How can you store named values? This sounds like a job for a dictionary!

Create a Dictionary

A dictionary is a list of named values, which means that each item in the list consists of a key and a value, often referred to as a key-value pair.

The syntax for a collection of data inside a dictionary with a list of named values, which is surrounded by curly braces, {}. Each item (key-value pair) has the syntax key: value.

The collection of data inside a dictionary is surrounded by curly braces, {}. Each item (key-value pair) has the syntax key: value. Keys must be unique in the dictionary and can be quoted strings, numbers, or tuples. Each key can have any value of any type. The items inside a dictionary are separated by commas. Since dictionaries can be rather lengthy, you can format a dictionary in a manner that's visually easier for you to read.

The syntax for creating a dictionary where each key can have any value of any type. The items inside a dictionary are separated by commas.

The following are grades for a recent math test. On the left, the name of the student is provided, and on the right, the grade that they received on the test is provided.

are grades for a recent math test. On the left, the name of the student is provided, and on the right, the grade that they received on the test is provided

Let's create a dictionary called math_test to store everyone's test ...

Get Bite-Size Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.