When is a hash map faster than an array, and when is the array the better choice?
A dictionary is faster when you are looking things up by a key. A list is faster when you are working with the items in order, or when the keys are small whole numbers.
So what is the difference in the work? A list keeps its items in a row, so finding one means going through them one at a time. A dictionary works out where the value is kept from the key itself, so it goes straight there.
the operation a list a dictionary
------------------------- ------------ ---------------
look up by value O(n) O(1) on average
look up by index O(1) O(1)
keep the order yes usually no
how much memory less more
how fast to add to the end O(1) O(1) on average
So when is the dictionary the better choice? When you look things up by name or by key, and when the keys are not small whole numbers. A list of a million items that you search through is slow, and a dictionary of the same items is fast.
And when is the list the better choice? Three cases. When the keys are whole numbers in a small range, because then you can use the number as the position and there is no lookup at all. When you need the order to be kept, because a dictionary has no order of its own. And when the data is small, because the dictionary has a fixed cost of its own.
There is one more thing worth knowing. A dictionary does not keep the order of the values, and in Python the dictionaries from before version 3.7 had no order at all. If you need both a lookup by key and the order, then you keep both, or you use an ordinary dictionary in a modern Python and rely on it.
The next question in this topic shows the difference in the code.