'In Python, when to use a Dictionary, List or Set?
When should I use a dictionary, list or set?
Are there scenarios that are more suited for each data type?
Solution 1:[1]
- 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 2:[2]
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 3:[3]
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 4:[4]
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
andx 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 ofx
inl
(at or afteri
and beforej
indeces)
A list also implements all of the mutable sequence operations:
l[i] = x
- itemi
ofl
is replaced byx
l[i:j] = t
- slice ofl
fromi
toj
is replaced by the contents of the iterablet
del l[i:j]
- same asl[i:j] = []
l[i:j:k] = t
- the elements ofl[i:j:k]
are replaced by those oft
del l[i:j:k]
- removes the elements ofs[i:j:k]
from the listl.append(x)
- appendsx
to the end of the sequencel.clear()
- removes all items froml
(same as dell[:]
)l.copy()
- creates a shallow copy ofl
(same asl[:]
)l.extend(t)
orl += t
- extendsl
with the contents oft
l *= n
- updatesl
with its contents repeatedn
timesl.insert(i, x)
- insertsx
intol
at the index given byi
l.pop([i])
- retrieves the item ati
and also removes it froml
l.remove(x)
- remove the first item froml
wherel[i]
is equal to xl.reverse()
- reverses the items ofl
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.
Solution 5:[5]
For C++ I was always having this flow chart in mind: In which scenario do I use a particular STL container?, so I was curious if something similar is available for Python3 as well, but I had no luck.
What you need to keep in mind for Python is: There is no single Python standard as for C++. Hence there might be huge differences for different Python interpreters (e.g. CPython, PyPy). The following flow chart is for CPython.
Additionally I found no good way to incorporate the following data structures into the diagram: bytes
, byte arrays
, tuples
, named_tuples
, ChainMap
, Counter
, and arrays
.
OrderedDict
anddeque
are available viacollections
module.heapq
is available from theheapq
moduleLifoQueue
,Queue
, andPriorityQueue
are available via thequeue
module which is designed for concurrent (threads) access. (There is also amultiprocessing.Queue
available but I don't know the differences toqueue.Queue
but would assume that it should be used when concurrent access from processes is needed.)dict
,set
,frozen_set
, andlist
are builtin of course
For anyone I would be grateful if you could improve this answer and provide a better diagram in every aspect. Feel free and welcome.
PS: the diagram has been made with yed. The graphml file is here
Solution 6:[6]
Although this doesn't cover set
s, it is a good explanation of dict
s and list
s:
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.
Solution 7:[7]
In combination with lists, dicts and sets, there are also another interesting python objects, OrderedDicts.
Ordered dictionaries are just like regular dictionaries but they remember the order that items were inserted. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
OrderedDicts could be useful when you need to preserve the order of the keys, for example working with documents: It's common to need the vector representation of all terms in a document. So using OrderedDicts you can efficiently verify if a term has been read before, add terms, extract terms, and after all the manipulations you can extract the ordered vector representation of them.
Solution 8:[8]
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.
Solution 9:[9]
When use them, I make an exhaustive cheatsheet of their methods for your reference:
class ContainerMethods:
def __init__(self):
self.list_methods_11 = {
'Add':{'append','extend','insert'},
'Subtract':{'pop','remove'},
'Sort':{'reverse', 'sort'},
'Search':{'count', 'index'},
'Entire':{'clear','copy'},
}
self.tuple_methods_2 = {'Search':'count','index'}
self.dict_methods_11 = {
'Views':{'keys', 'values', 'items'},
'Add':{'update'},
'Subtract':{'pop', 'popitem',},
'Extract':{'get','setdefault',},
'Entire':{ 'clear', 'copy','fromkeys'},
}
self.set_methods_17 ={
'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
'Subtract':{'pop', 'remove','discard'},
'Relation':{'isdisjoint', 'issubset', 'issuperset'},
'operation':{'union' 'intersection','difference', 'symmetric_difference'}
'Entire':{'clear', 'copy'}}
Solution 10:[10]
Dictionary: A python dictionary is used like a hash table with key as index and object as value.
List: A list is used for holding objects in an array indexed by position of that object in the array.
Set: A set is a collection with functions that can tell if an object is present or not present in the set.
Solution 11:[11]
May be off topic in terms of the question OP asked-
- List: A unhashsable collection of ordered, mutable objects.
- Tuple: A hashable collection of ordered, immutable objects, like list.
- Set: An unhashable collection of unordered, mutable and distinct objects.
- Frozenset: A hashable collection of unordered, immutable and distinct objects.
- Dictionary : A unhashable,unordered collection of mutable objects that maps hashable values to arbitrary values.
To compare them visually, at a glance, see the image-
Solution 12:[12]
Dictionary: When you want to look up something using something else than indexes. Example:
dictionary_of_transport = {
"cars": 8,
"boats": 2,
"planes": 0
}
print("I have the following amount of planes:")
print(dictionary_of_transport["planes"])
#Output: 0
List and sets: When you want to add and remove values.
Lists: To look up values using indexes
Sets: To have values stored, but you cannot access them using anything.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow