Dictionary versus Nested list/array?

Question:

In Python, dictionaries are used for key/value pairs. Nested lists, or arrays, however, can do the same thing with two-value lists inside a big list, for example [[1, 2], [3, 4]].

Arrays have more uses and are actually faster, but dictionaries are more straightforward. What are the pros and cons of using a dictionary versus an array?

Asked By: Enderman

||

Answers:

If you use a list of key/value pairs, getting the value corresponding to a key requires a linear search, which is O(n). If the list is sorted by the keys you can improve that to O(log n), but then adding to the list becomes more complicated and expensive since you have to keep it sorted.

Dictionaries are implemented as hash tables, so getting the value corresponding to a key is amortized constant time.

Furthermore, Python provides convenient syntax for looking up keys in a dictionary. You can write dictname[key]. Since lists aren’t intended to be used as lookup tables, there’s no corresponding syntax for finding a value by key there. listname[index] gets an element by its numeric position, not looking up the key in a key/value pair.

Of course, if you want to use an association list, there’s nothing stopping you from writing your own functions to do so. You could also embed them in a class and define appropriate methods so you can use [] syntax to get and set them.

Answered By: Barmar
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.