Dictionaries¶
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
- Hashable
- Unique within the dictionary
Hashability
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.
# The keys here are the element symbols,
# The values are the melting points in Kelvin
melting_points = {
"Hydrogen": 14.01,
"Helium": 0.95,
"Lithium": 453.7,
"Beryllium": 1560,
"Boron": 2365
}
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.
melting_points["Unobtanium"] = -100 # Create an new key-value pair
# Oops, we have a typo here, let's override the value with the correct one
melting_points["Unobtanium"] = 100 # Much better!
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.
The keyword 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 .get(…)
-function to
- return a value for the key or
- provide a default value otherwise
instead of ending up in an error.
Deleting Values¶
To only delete the value, but keep the key the canonical way is to set the value to None
.
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 .items()
or .values(…)
, depending on what one wants to loop over.
The .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.