A dictionary or associative array data type is a collection of unique key-value pairs so they do not duplicate.
The features
The collections mentioned earlier, namely, lists and tuples, are ordered and store elements in the order we add them. Dictionaries are different. They do not remember the order in which we add items, and instead, store items so that operations on the dictionary contents are as efficient as possible:
Strictly speaking, as of Python 3.7, the internal structure of dictionaries has changed: as of this version, dictionaries remember the order in which we added keys. However, we do not need to tie logic to this property-lists are better for storing the order of things.
Lists and tuples are indexed. It means the position of each element is a number — an ordinal number from the beginning of the collection. Dictionary keys do not have to be numbers. They can be many other types of data, most often strings. There are no specific patterns between the dictionary keys except for the uniqueness guarantee, when the indexes of the list and the tuple are consistent with no omissions, and the increment between elements is one.
Lists usually are homogeneous. They store elements of the same type. On the other hand, dictionaries usually are heterogeneous. Both the types of values and the types of keys can be different — yes, this happens, but rarely.
The reasons to use dictionaries
It is convenient to save sets of information about an entity in dictionaries. For example, a user may have a nickname, age, and email address. And we can store all this data in one dictionary:
user = {
'name': 'superbob',
'email': 'bob.is.super@mail.com',
'age': 35
}
It is what a dictionary literal looks like:
- Here
'name'
,'email'
and'age'
are dictionary keys - And
'superbob'
,'bob.is.super@mail.com'
and35
are clearly values
Similarly, using dictionaries, you can describe any entities in the subject area, for example, an order, a course, a lesson, a topic on a forum, or a comment on a project. It will have its structure in each case, depending on the properties that describe a particular entity.
In addition, we can use dictionaries as repositories to configure parameters or pass a lot of heterogeneous data to a function in the form of a single parameter.
Are there any more questions? Ask them in the Discussion section.
The Hexlet support team or other students will answer you.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.