Mark As Completed Discussion

Dictionaries

A collection of data can also be stored in the form of dictionaries in Python. Unlike lists, dictionaries store data values in what's known as key: value pairs. These key: value pairs are also called items. This means that in a dictionary, values are assigned to keys, and the values of these items can be obtained using key names.

In Python, dictionaries are declared using curly braces {}, separated by a comma. A key is specified within the curly braces, which is followed by a colon and its corresponding value.

Let's look at an example dictionary.

Dictionaries

But in what cases can dictionaries be helpful?

Suppose you want to store distances of all cities from a chosen starting point. In such a case, it would be helpful if you could store distance values for each city from the starting city. Using a list would be a tedious task as you would have difficulty representing which city has what distance. Dictionaries make it easier to represent such problems. In this example, using a dictionary, cities can be represented as keys and their distances as values.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment