Dictionaries#
This notebook introduces the dict (short for ‘dictionary’) container of Python. Dicts are omnipresent in Python and are used to store key-value pairs, and one of the most important data structures you will come across during this school. They are mutable, meaning you can change their contents after creation, and they are unordered, meaning that the order of items is not guaranteed.
This notebook also provides some usage examples of the basic interface in the context of how some of the ESS software uses dicts.
You can also find exercises in the ‘Sequence data types’ notebook, but this goes a little deeper.
See https://docs.python.org/3/library/stdtypes.html#dict or use help(dict) for a complete description of the interface.
Insertion and extraction#
Create a dict using a ‘literal’:
coords = {'x': 2, 'y': 3}
coords
{'x': 2, 'y': 3}
Get the element with key ‘x’:
coords['x']
2
Trying to get an element with a key that is not in the dict fails:
coords['z']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[4], line 1
----> 1 coords['z']
KeyError: 'z'
Insert a new element:
coords['z'] = 4
coords['z']
4
coords
{'x': 2, 'y': 3, 'z': 4}
Overwrite an existing element:
coords['x'] = -1
coords
{'x': -1, 'y': 3, 'z': 4}
Remove an element:
del coords['y']
coords
{'x': -1, 'z': 4}
Looping#
Loop over the keys:
for key in coords.keys():
print(key)
x
z
Also possible without .keys():
for key in coords:
print(key)
x
z
Get the value for each key:
for key in coords.keys():
value = coords[key]
print(key, value)
x -1
z 4
Better:
for key, value in coords.items():
print(key, value)
x -1
z 4
Merging#
Merge 2 or more dicts:
xy = {'x': 1.2, 'y': 3.4}
uv = {'u': 10, 'v': 20}
combined = {**xy, **uv}
combined
{'x': 1.2, 'y': 3.4, 'u': 10, 'v': 20}
Merge dicts and add an extra item:
combined_with_z = {**xy, **uv, 'z': 5.6}
combined_with_z
{'x': 1.2, 'y': 3.4, 'u': 10, 'v': 20, 'z': 5.6}
Merging can overwrite items: (last item in wins)
xyz = {'x': 1.2, 'y': 3.4, 'z': 5.6}
ux = {'u': 10, 'x': 20}
combined = {**xyz, **ux, 'z': -1}
combined
{'x': 20, 'y': 3.4, 'z': -1, 'u': 10}
Different key types#
Can use many different types as keys, including types themselves:
type_descriptions = {
int: 'integer',
complex: 'partly imaginary',
str: 'text'
}
type_descriptions[str]
'text'
for key in type_descriptions.keys():
print(key)
<class 'int'>
<class 'complex'>
<class 'str'>
Different value types
Can use any type as values:
def add(a, b):
return a + b
def sub(a, b):
return a - b
operations = {'add': add, 'sub': sub}
operations['sub'](3, 5)
-2
operations['add'](3, 5)
8