In Python, when to use a Dictionary, List or Set?
- Do you just need an ordered sequence of items? Go for a list.
- Do you just need to know whether or not you've already got a particular value, but without ordering (and you don't need to store duplicates)? Use a set.
- Do you need to associate values with keys, so you can look them up efficiently (by key) later on? Use a dictionary.
A list
keeps order, dict
and set
don't: when you care about order, therefore, you must use list
(if your choice of containers is limited to these three, of course ;-) ).
dict
associates each key with a value, while list
and set
just contain values: very different use cases, obviously.
set
requires items to be hashable, list
doesn't: if you have non-hashable items, therefore, you cannot use set
and must instead use list
.
set
forbids duplicates, list
does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter
-- you could build one as a dict
, if for some weird reason you couldn't import collections
, or, in pre-2.7 Python as a collections.defaultdict(int)
, using the items as keys and the associated value as the count).
Checking for membership of a value in a set
(or dict
, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set
is better than list
.