dict - Presentation#

This notebook introduces the dict container of Python. It provides some usage examples of the basic interface in the context of how Scipp uses dicts. You can find exercises in the ‘Sequence data types’ notebook. See https://docs.python.org/3/library/stdtypes.html#dict or use help(dict) for a complete description of the interface.

dicts and dict-like data structures are used a lot throughout the Scipp ecosystem. For example:

  • Coordinates: da.coords is a dict-like container.

  • Coordinate transformations: {'wavelength': wavelength_from_tof, 'two_theta': two_theta_with_gravity}

  • Workflows: Parameter insertion and access works like a dict (wf[NBins] = bins)

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