In Python, are there any advantages / disadvantages of working with a list of lists versus working with a dictionary, more specifically when doing numerical operations with them? I'm writing a class of functions to solve simple matrix operations for my linear algebra class. I was using dictionaries, but then I saw that numpy
uses list of lists instead, so I guess there must be some advantages in it.
Example: [[1,2,3],[4,5,6],[7,8,9]]
as opposed to {0:[1,2,3],1:[4,5,6],2:[7,8,9]}
The list is an ordered collection of data, whereas the dictionaries store the data in the form of key-value pairs using the hashtable structure.
A list is an ordered sequence of objects, whereas dictionaries are unordered sets. However, the main difference is that items in dictionaries are accessed via keys and not via their position.
The reason is because a dictionary is a lookup, while a list is an iteration. Dictionary uses a hash lookup, while your list requires walking through the list until it finds the result from beginning to the result each time.
A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values. In this article, we will discuss the same in a tabular form.
When the keys of the dictionary are 0
, 1
, ..., n
, a list
will be faster, since no hashing is involved. As soon as the keys are not such a sequence, you need to use a dict
.
I think this largely depends on how you plan on using this structure.
Python's dictionaries are (like most) unordered by default. If you plan on iterating over your data like such, you shouldn't use a dictionary:
for list in dict.keys():
for elem in list:
# Logic
Likewise, it doesn't make a lot of sense to use a dictionary with the keys 1, 2, 3 ... when they have little value other than an index. Dictionaries also take up more space in memory due to the hashing process.
If you plan on accessing items by element (which it sounds like you want to), you'll still want to use a List. Index lookup in a list of O(1), same as in a Dictionary. The only difference is when you're looking up some key value, instead of an index (which will be faster than in a dictionary).
You should really only consider using a dictionary when you have some sort of key-value relationship mapping, in which a meaningful key needs to be searched for to retrieve a related value. This doesn't sound like one of those cases. Stick with a list-of-lists.
That's not to say Dictionaries are a bad data structure. Ruby and Python introduced me to them, and they're extremely useful for any of those afore-mentioned mapping problems (which I find I run into quite a lot). They're just useful for a specific class of problems, and this isn't one of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With