File: union_dict.rst

package info (click to toggle)
python-cogent 2024.5.7a1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 74,600 kB
  • sloc: python: 92,479; makefile: 117; sh: 16
file content (68 lines) | stat: -rw-r--r-- 1,584 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
.. _union_dict:

``UnionDict`` -- a dict with set like operations and keys as attributes
=======================================================================

This object combines the key-element storage of a ``dict`` with the union operation of a ``set()`` object. It is used in the ``cogent3.draw`` module, primarily for the ``figure`` and ``layout`` attributes.

Accessing elements of a ``UnionDict``
-------------------------------------

Keys in a ``UnionDict`` can be accessed like attributes

.. jupyter-execute::

    from cogent3.util.union_dict import UnionDict

    data = UnionDict(a=2, b={"c": 24, "d": [25]})
    data.a

.. jupyter-execute::

    data["a"]

.. jupyter-execute::

    data.b.d

Updating a ``UnionDict``
------------------------

If you use the ``|`` bitwise operator to compare two dicts and the left one is a ``UnionDict``, a union operation is performed.

.. jupyter-execute::

    from cogent3.util.union_dict import UnionDict

    data = UnionDict(a=2, b={"c": 24, "d": [25]})
    data.b |= {"d": 25}
    data.b

This can also be done using the ``union`` method.

.. jupyter-execute::

    data.b.union({"d": [25]})

.. jupyter-execute::

    data.b
    {"c": 24, "d": [25]}

Accessing a non-existent ``UnionDict`` key
------------------------------------------

.. jupyter-execute::
    :raises: KeyError

    from cogent3.util.union_dict import UnionDict

    data = UnionDict(a=2, b={"c": 24, "d": [25]})
    data["k"]

But if accessing as an attribute, you get an attribute error.

.. jupyter-execute::
    :raises: AttributeError

    data.k