I could represent any list as a dictionary whose keys are the valid list indices, and whose values are the list's items. E.g., [5, 6, 'a']
would be represented as {0:5, 1:6, 2:'a'}
.
In terms of asymptotic time and memory complexity, the dict
representation is identical to list
. list
uses less memory by a constant factor.
If memory is not an issue, is it true that I can always use dict
instead of lists and other sequences (to gain the flexibility of using arbitrary keys, and to slightly standardize the code by reducing the number of different containers used)?
Prefer the data structure that makes the most sense given the data going into it.
dict
s are great, but, for example, they don't hold order: so if you want to iterate over the values in order you will have to sort based on key, which produces complexity and makes it hard to read.
In general, it's unlikely that using dict
s everywhere instead of list
s will make meaningful speed increases to your application - it's premature optimization.
What is far more important is what makes sense to readers and modifiers of your code, and what is most suitable for the data you are trying to store. Where you are storing a sequence of data, use a list
. Where you are storing a mapping, use a dict
.