Dictionary
Let's take a look at another Python composite data type, called
dictionary, which is similar to a list in that it is a collection of objects.
Dictionaries and lists have the following characteristics:
- both are mutable;
- both are dynamic (can grow and shrink as needed);
- both can be nested (a list can contain another list, a dictionary can contain another dictionary, a dictionary can also contain a list, and vice versa).
Dictionaries differ from lists primarily in how elements are accessed:
- list elements are accessed by their position in the list through indexing;
- Dictionary elements are accessed using keys.
Dictionaries are a data structure implemented in Python, better known as an associative array. A dictionary consists of a set of key pairs -value. Each key-value pair maps the key to the corresponding value.
Creating a dictionary
You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces (
{}
). A colon (
:
) separates each key from its associated one values:
d = {
<key>: <value>,
<key>: <value>,
.
.
.
<key>: <value>
}
You can create a dictionary with the built-in dict()
function. The dict()
argument must be a sequence of key-value
pairs. A list of tuples works well for this:
d = dict([
(<key>, <value>),
(<key>, <value),
.
.
.
(<key>, <value>)
])
You can display the contents of the list on the screen simply with the print()
command. Entries in the dictionary are displayed in the order in which they were created.