What are Dictionaries?¶
While lists or tuples hold a sequence of singular values, dictionaries hold a sequence of associations between a key and a value. Values can be of any data type. Keys need to be
- Unique within the dictionary
Hashable means that a mathematical function called a hash can be
calculated on the data. This is the case for most basic data types like
bool, string, integer, float, and many others. Non-hashable types
are for example lists or dictionaries themselves.
If in doubt, one can try the built-in
hash(…)-function to check.
As the name implies, this makes dictionaries a good data structure if you need to store data in which you often look things up.
Creating a Dictionary¶
Let’s say we have an association between elements and their melting points.
Adding or Modifying Values¶
Contrary to lists or strings, dictionaries do not use an index to access an entry.
Instead, when giving a key within the
[…], the value is returned.
The access via a key can be also used to set values or enter new values.
Dealing with Missing Keys¶
Accessing a key in a dictionary that does not exist, will lead to a so called key error.
Check if a Key exists¶
Sometimes it is not clear if a given key is in the dictionary.
in can be used to check for this.
Access Values with a Fallback¶
Instead of checking each time before looking up a value, dictionaries offer the
- return a value for the key or
- provide a default value otherwise
instead of ending up in an error.
To only delete the value, but keep the key the canonical way is to set the value to
To delete the whole key-value pair, the
del keyword can be used.
Looping over Dictionaries¶
When looping over a dictionary, the loop variable will be the current key of the key-value pair.
Another approach would be to use the dictionaries’ method
.values(…), depending on what one wants to loop over.
.items()-method returns a sequence of key-value pairs, so you might want to unpack those to effectively give you two loop variables.
Note that with the
.values()-method, you do not have any direct access to the associated keys, so it’s use is very situational.