Dictionaries and Sets

Dictionaries and Sets#

Dictionaries#

Just like the physical dictionaries used to look up the meaning of a word, dictionaries in Python are data structures that associate keys to values. In other programming languages, they are also known as hash tables, hash maps or associative arrays.

Dictionaries are ordered in Python 3.7 and higher, in Python 3.6 and lower they are an unordered collection of key:value pairs. They are changeable, meaning that a dictionary can be updated, and values can be added, removed and overwritten.

Note: Keys in a dictionary are unique (duplicates are not allowed), this means that the values can be overwritten.

They are written in curly brackets.

dict_conditions = {
    "temperature": 30,
    "pH": 7.0,
    "pressure": 1.0,
    "pH": 6.9
}

print(dict_conditions)
{'temperature': 30, 'pH': 6.9, 'pressure': 1.0}

As you can see, the pH was overwritten!

But you can also have a list of values corresponding to each key.

dict_conditions = {
    "temperature": [30, 29, 28],
    "pH": [7.0, 6.9, 6.8],
    "pressure": [1.0, 1.5, 2.0]
}

print(dict_conditions)
{'temperature': [30, 29, 28], 'pH': [7.0, 6.9, 6.8], 'pressure': [1.0, 1.5, 2.0]}

Let’s see how to extract information from dictionaries below

# Print the values of temperature
print(dict_conditions["temperature"])
# or
print(dict_conditions.get("temperature"))

# Look if a key is in the dictionary
print("pressure" in dict_conditions)
print("air pressure" in dict_conditions)

# Update a certain condition
dict_conditions["temperature"] = 30
print(dict_conditions)
[30, 29, 28]
[30, 29, 28]
True
False
{'temperature': 30, 'pH': [7.0, 6.9, 6.8], 'pressure': [1.0, 1.5, 2.0]}

Let’s now extract all keys, values and items in the dictionary.

# Extrct the keys
print(dict_conditions.keys())

# Extrct the values
print(dict_conditions.values())

# Extrct the items to get the tuple of keys and values
print(dict_conditions.items())
dict_keys(['temperature', 'pH', 'pressure'])
dict_values([30, [7.0, 6.9, 6.8], [1.0, 1.5, 2.0]])
dict_items([('temperature', 30), ('pH', [7.0, 6.9, 6.8]), ('pressure', [1.0, 1.5, 2.0])])

Creating a dictionary#

Dictionaries can be created in many ways. We can manually create a collection of keys and values, as seen above, or we can create them through iteration.

Let’s see other ways of creating a dictionary.

# Create a dictionary in a loop
list_numbers = ['zero', 'one', 'two', 'three', 'four', 'five']

my_dictonary = {}
for key, value in enumerate(list_numbers): #enumerate is a function used to get a counter 
                                           #and the value of an iterable (in our case a list)
    my_dictonary[key] = value
    
print(my_dictonary)
{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

Or we can do it in a one-liner.

my_dictonary = {key:value for key, value in enumerate(list_numbers)}
print(my_dictonary)
{0: 'zero', 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five'}

Sets#

A set is a unique and unordered collection of items. The order of the items in a set does not matter.

Items in a set cannot be changed, but they can be removed and new items can be added to the set.

Let’s see how to define a set below.

experiments = ['Bubble column', 'Fluid bed', 'Crystallization', 'Ion exchange', 
               'Solid-liquid extraction', 'Crystallization']

set_experiments = set(experiments)
print(set_experiments)
{'Ion exchange', 'Crystallization', 'Fluid bed', 'Solid-liquid extraction', 'Bubble column'}

But remember that items in a set cannot be indexed!

print(set_experiments[0])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18812/2900422087.py in <module>
----> 1 print(set_experiments[0])

TypeError: 'set' object is not subscriptable

Sets operations#

Sets allow different operations, like intersection, union and difference between two collections.

multiples_three = {3, 6, 9, 12, 15, 18, 21, 24, 27, 30}
even_numbers = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20}

# Intersection
intersection = set(multiples_three & even_numbers) # or multiples_three.intersection(even_numbers)
print(intersection)

# Union
union = set(multiples_three | even_numbers) # or multiples_three.union(even_numbers)
print(union)

# A-B: note that B-A will lead to a different result
difference = multiples_three - even_numbers
print(difference)

# Subsets contained in a set (if all elements in 'multiples_three' are in 'union'
subset = multiples_three.issubset(union)
print(subset)
{18, 12, 6}
{2, 3, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20, 21, 24, 27, 30}
{3, 9, 15, 21, 24, 27, 30}
True

Let’s now try to remove elements

print(difference)
difference.remove(3)
difference
{3, 9, 15, 21, 24, 27, 30}
{9, 15, 21, 24, 27, 30}
difference.pop()
9