Dictionaries#
Dictionaries are data structures that hold key-value pairs, written as key:value
.
See also
You can define dictionary like this:
german_english_dictionary = {'Vorlesung':'Lecture', 'Gleichung':'Equation'}
For readers convenience, consider writing them 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'}
You can also retrieve a list of all keys in the dictionary:
keys = list(german_english_dictionary.keys())
keys
['Vorlesung', 'Gleichung', 'Tag']
keys[1]
'Gleichung'
Tables#
Tables can be expressed as dictionaries with arrays as elements.
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]
You 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 circlea area measurements.
r1 = 12
r2 = 8
r3 = 15