When should I use a dictionary, list or set?
Are there scenarios that are more suited for each data type?
Lists are slightly faster than sets when you just want to iterate over the values. Sets, however, are significantly faster than lists if you want to check if an item is contained within it. They can only contain unique items though.
Usage: Use a dictionary when you have a set of unique keys that map to values and to use a list if you have an ordered collection of items.
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. Due to this, fetching the elements from the list data structure is quite complex compared to dictionaries in Python. Therefore, the dictionary is faster than a list in Python.
The sets are an unordered collection of data types. These are mutable, iterable, and do not consist of any duplicate elements. In Python, the dictionary refers to a collection (unordered) of various data types.
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
.
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