Python for the Energy Industry
This lesson covers a couple of other ways of storing data in Python that you will come across: tuples and dictionaries.
Tuples function very similarly to lists, with one key difference: once a tuple is created, it cannot be modified. Tuples are created using round, rather than square brackets.
counts = (3,5,7,10)
print(counts)
(3, 5, 7, 10)
# Indexing works the same for tuples as lists
print('First item:', counts[0])
print('Second item:', counts[1])
First item: 3 Second item: 5
# Trying to modify the tuple gives an error
# uncomment the following line:
# counts[0] = 4
Dictionaries store pairs of variables: the 'key' and the 'value'. The key can be used instead of an index to access the value. Here's an example dictionary for storing the cubic capacity of different vessels:
capacities = {'ABIOLA': 47261, 'ABLIANI': 124518, 'ACACIA': 14570}
print(capacities['ABLIANI'])
124518
It is straightforward to add new items to a dictionary:
capacities['A STAR'] = 333924
print(capacities)
{'ABIOLA': 47261, 'ABLIANI': 124518, 'ACACIA': 14570, 'A STAR': 333924}
Using a loop to iterate over a dictionary will iterate over the keys:
for vessel in capacities:
print(vessel, 'capacity =', capacities[vessel])
ABIOLA capacity = 47261 ABLIANI capacity = 124518 ACACIA capacity = 14570 A STAR capacity = 333924
The keys and values can also be accessed separately from a dictionary:
print('keys -', list(capacities.keys()))
print('values -', list(capacities.values()))
keys - ['ABIOLA', 'ABLIANI', 'ACACIA', 'A STAR'] values - [47261, 124518, 14570, 333924]
Note: what's up with the pairs of brackets in keys() and values()? These are functions that act on the dictionary like append, pop etc. but which take no arguments. We will explore functions more in the next lesson.
Use a for
loop to find which vessel in capacities
has the largest capacity.