Dictionaries#
Dictionaries are data structures that hold key-value pairs, written as key:value
.
See also
You can define a dictionary like this:
german_english_dictionary = {'Vorlesung':'Lecture', 'Gleichung':'Equation'}
For readability reasons, consider writing it like this:
german_english_dictionary = {
'Vorlesung':'Lecture',
'Gleichung':'Equation'
}
german_english_dictionary
{'Vorlesung': 'Lecture', 'Gleichung': 'Equation'}
If you want to access a given entry in the dictionary, you can address it using square brackets []
and the key:
german_english_dictionary['Vorlesung']
'Lecture'
You can add elements to the dictionary:
german_english_dictionary['Tag'] = 'Day'
german_english_dictionary
{'Vorlesung': 'Lecture', 'Gleichung': 'Equation', 'Tag': 'Day'}
keys = list(german_english_dictionary.keys())
keys
['Vorlesung', 'Gleichung', 'Tag']
You can retrieve all keys from the dictionary as a list:
keys = list(german_english_dictionary.keys())
keys
['Vorlesung', 'Gleichung', 'Tag']
keys[1]
'Gleichung'
You can retrieve all values from the dictionary as a list:
values = list(german_english_dictionary.values())
values
['Lecture', 'Equation', 'Day']
Tables#
We can use dictionaries to build table-like structures. Here, the value of a key:value
pair is not a single value but a list of values, i.e., a column.
measurements_week = {
'Monday': [2.3, 3.1, 5.6],
'Tuesday': [1.8, 7.0, 4.3],
'Wednesday':[4.5, 1.5, 3.2],
'Thursday': [1.9, 2.0, 6.4],
'Friday': [4.4, 2.3, 5.4]
}
measurements_week
{'Monday': [2.3, 3.1, 5.6],
'Tuesday': [1.8, 7.0, 4.3],
'Wednesday': [4.5, 1.5, 3.2],
'Thursday': [1.9, 2.0, 6.4],
'Friday': [4.4, 2.3, 5.4]}
measurements_week['Monday']
[2.3, 3.1, 5.6]
We can also store variables in such tables:
w1 = 5
h1 = 3
area1 = w1 * h1
w2 = 2
h2 = 4
area2 = w2 * h2
rectangles = {
"width": [w1, w2],
"height": [h1, h2],
"area": [area1, area2]
}
rectangles
{'width': [5, 2], 'height': [3, 4], 'area': [15, 8]}
Exercise#
You just measured the radius of three circles. Write them into a table and add a column with corresponding circle area measurements.
r1 = 12
r2 = 8
r3 = 15