Skip to content

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.

print(melting_points["Hydrogen"])

14.01

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.

print(melting_points["Iron"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Iron'

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.

if "Hydrogen" in melting_points:
    print("We know the melting point of hydrogen")

We know the melting point of hydrogen

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.

print(melting_points.get("Hydrogen", None))
print(melting_points.get("Iron", None))
14.01
None

Deleting Values

To only delete the value, but keep the key the canonical way is to set the value to None.

melting_points["Unobtanium"] = None

To delete the whole key-value pair, the del keyword can be used.

del melting_points["Unobtanium"]

Looping over Dictionaries

When looping over a dictionary, the loop variable will be the current key of the key-value pair.

for element in melting_points:
    temperature = melting_points[element]
    print("Melting point of", element, "is", temperature, "K") 
Melting point of Hydrogen is 14.01 K
Melting point of Helium is 0.95 K
Melting point of Lithium is 453.7 K
Melting point of Beryllium is 1560 K
Melting point of Boron is 2365 K

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.

for (element, temperature) in melting_points.items():
    print("Melting point of", element, "is", temperature, "K") 
Melting point of Hydrogen is 14.01 K
Melting point of Helium is 0.95 K
Melting point of Lithium is 453.7 K
Melting point of Beryllium is 1560 K
Melting point of Boron is 2365 K

Note that with the .values()-method, you do not have any direct access to the associated keys, so it’s use is very situational.

for temperature in melting_points.values():
    # Note that we have no idea about the corresponding key in this case
    print("Melting point of some element is", temperature, "K") 
Melting point of some element is 14.01 K
Melting point of some element is 0.95 K
Melting point of some element is 453.7 K
Melting point of some element is 1560 K
Melting point of some element is 2365 K