In Python, when to use a Dictionary, List or Set?

202,196

Solution 1

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.

Solution 2

  • 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.

Solution 3

When you want an unordered collection of unique elements, use a set. (For example, when you want the set of all the words used in a document).

When you want to collect an immutable ordered list of elements, use a tuple. (For example, when you want a (name, phone_number) pair that you wish to use as an element in a set, you would need a tuple rather than a list since sets require elements be immutable).

When you want to collect a mutable ordered list of elements, use a list. (For example, when you want to append new phone numbers to a list: [number1, number2, ...]).

When you want a mapping from keys to values, use a dict. (For example, when you want a telephone book which maps names to phone numbers: {'John Smith' : '555-1212'}). Note the keys in a dict are unordered. (If you iterate through a dict (telephone book), the keys (names) may show up in any order).

Solution 4

  • Use a dictionary when you have a set of unique keys that map to values.

  • Use a list if you have an ordered collection of items.

  • Use a set to store an unordered set of items.

Solution 5

In short, use:

list - if you require an ordered sequence of items.

dict - if you require to relate values with keys

set - if you require to keep unique elements.

Detailed Explanation

List

A list is a mutable sequence, typically used to store collections of homogeneous items.

A list implements all of the common sequence operations:

  • x in l and x not in l
  • l[i], l[i:j], l[i:j:k]
  • len(l), min(l), max(l)
  • l.count(x)
  • l.index(x[, i[, j]]) - index of the 1st occurrence of x in l (at or after i and before j indeces)

A list also implements all of the mutable sequence operations:

  • l[i] = x - item i of l is replaced by x
  • l[i:j] = t - slice of l from i to j is replaced by the contents of the iterable t
  • del l[i:j] - same as l[i:j] = []
  • l[i:j:k] = t - the elements of l[i:j:k] are replaced by those of t
  • del l[i:j:k] - removes the elements of s[i:j:k] from the list
  • l.append(x) - appends x to the end of the sequence
  • l.clear() - removes all items from l (same as del l[:])
  • l.copy() - creates a shallow copy of l (same as l[:])
  • l.extend(t) or l += t - extends l with the contents of t
  • l *= n - updates l with its contents repeated n times
  • l.insert(i, x) - inserts x into l at the index given by i
  • l.pop([i]) - retrieves the item at i and also removes it from l
  • l.remove(x) - remove the first item from l where l[i] is equal to x
  • l.reverse() - reverses the items of l in place

A list could be used as stack by taking advantage of the methods append and pop.

Dictionary

A dictionary maps hashable values to arbitrary objects. A dictionary is a mutable object. The main operations on a dictionary are storing a value with some key and extracting the value given the key.

In a dictionary, you cannot use as keys values that are not hashable, that is, values containing lists, dictionaries or other mutable types.

Set

A set is an unordered collection of distinct hashable objects. A set is commonly used to include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.

Share:
202,196
Blankman
Author by

Blankman

... .. . blank

Updated on October 01, 2021

Comments

  • Blankman
    Blankman over 2 years

    When should I use a dictionary, list or set?

    Are there scenarios that are more suited for each data type?