Skip to content

Commit

Permalink
📝 Update dict type
Browse files Browse the repository at this point in the history
  • Loading branch information
veit committed Dec 27, 2024
1 parent a7ce07c commit 5b8c0d2
Showing 1 changed file with 86 additions and 95 deletions.
181 changes: 86 additions & 95 deletions docs/types/dicts.rst
Original file line number Diff line number Diff line change
@@ -1,45 +1,89 @@
Dictionaries
============

Python’s built-in dictionary data type provides associative array functionality
implemented using hash tables. The built-in ``len`` function returns the number
of key-value pairs in a dictionary. The ``del`` statement can be used to delete
a key-value pair. As with :doc:`sequences-sets/lists` , several dictionary
methods (:py:meth:`clear <dict.clear>`, :py:meth:`copy <dict.copy>`,
:py:meth:`get <dict.get>`, :py:meth:`items <dict.items>`, :py:meth:`keys
<dict.keys>`, :py:meth:`update <dict.update>` and :py:meth:`values
<dict.values>`) are available.

.. code-block:: pycon
>>> x = {1: "eins", 2: "zwei"}
>>> x[3] = "drei"
>>> x["viertes"] = "vier"
>>> list(x.keys())
[1, 2, 3, 'viertes']
>>> x[1]
'eins'
>>> x.get(1, "nicht vorhanden")
'eins'
>>> x.get(5, "nicht vorhanden")
'nicht vorhanden'
Keys must be of immutable type, including :doc:`numbers/index`,
:doc:`strings/index` and :doc:`sequences-sets/tuples`.
Dictionaries consist of key-value pairs. Keys must be of invariant type,
including numbers, :doc:`strings/index` and :doc:`sequences-sets/tuples`.

.. warning::
Even if you can use different key types in a dictionary, you should avoid
this, as it not only makes it more difficult to read, but also sorting is
also made more difficult.
doing so, as this not only makes it more difficult to read, but also to sort.

Values can be any type of object, including mutable types such as
:doc:`sequences-sets/lists` and :doc:`dicts`. If you try to access the value of
a key that is not in the dictionary, a ``KeyError`` exception is thrown. To
avoid this error, the dictionary method ``get`` optionally returns a custom
value if a key is not contained in a dictionary.
:doc:`sequences-sets/lists` and :doc:`dicts`.

.. code-block:: pycon
>>> dict = {
... "2022-01-31": -0.751442,
... "2022-02-01": 0.816935,
... "2022-02-02": -0.272546,
... }
>>> dict["2022-02-03"] = -0.268295
If you try to access the value of a key that is not contained in the dictionary,
a ``KeyError`` exception is thrown. To avoid this error, the dictionary method
``get`` optionally returns a user-defined value if a key is not contained in a
dictionary.

.. code-block:: pycon
>>> dict["2022-02-03"]
-0.268295
>>> dict["2022-02-04"]
Traceback (most recent call last):
File "<python-input-15>", line 1, in <module>
dict["2022-02-04"]
~~~~^^^^^^^^^^^^^^
KeyError: '2022-02-04'
>>> dict.get("2022-02-03", "Messwert nicht vorhanden")
-0.268295
>>> dict.get("2022-02-04", "Messwert nicht vorhanden")
'Messwert nicht vorhanden'
Other Dict methods
------------------

The :func:`len` function built into Dicts returns the number of key-value pairs.
The ``del`` statement can be used to delete a key-value pair. As with
:doc:`sequences-sets/lists`, several dictionary methods ((:py:meth:`clear
<dict.clear>`, :py:meth:`copy <dict.copy>`, :py:meth:`get <dict.get>`,
:py:meth:`items <dict.items>`, :py:meth:`keys <dict.keys>`, :py:meth:`update
<dict.update>` and :py:meth:`values <dict.values>`) are available.

The :py:meth:`keys <dict.keys>`, :py:meth:`values <dict.values>` and
:py:meth:`items <dict.items>` methods do not return lists, but dictionary view
objects that behave like sequences, but are updated dynamically when the
dictionary changes. For this reason, you must use the :func:`list` function so
that they become a list in these examples:

.. code-block:: pycon
>>> list(dict.keys())
['2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03']
As of Python 3.6, dictionaries retain the order in which the keys were created,
and they are also returned in this order with :py:meth:`keys <dict.keys>`.

Merging dictionaries
~~~~~~~~~~~~~~~~~~~~

You can use the :py:meth:`dict.update` method to merge two dictionaries into a
single dictionary:

.. code-block:: pycon
>>> titles = {7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}
>>> new_titles = {7.0: "Data types", 7.3: "Sets"}
>>> titles.update(new_titles)
>>> titles
{7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}
.. note::
The order of the operands is important, as ``7.0`` is duplicated and the
value of the last key overwrites the previous one.

``setdefault``
--------------
~~~~~~~~~~~~~~

:py:meth:`setdefault <dict.setdefault>` can be used to provide counters for the
keys of a dict, for example:
Expand All @@ -65,84 +109,31 @@ keys of a dict, for example:
>>> collections.Counter(titles)
Counter({'Lists': 2, 'Data types': 1, 'Sets': 1})
Merging dictionaries
--------------------

You can merge two dictionaries into a single dictionary using the
:py:meth:`dict.update` method:

.. code-block:: pycon
>>> titles = {7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}
>>> new_titles = {7.0: "Data types", 7.3: "Sets"}
>>> titles.update(new_titles)
>>> titles
{7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}
.. note::
The order of the operands is important, as ``7.0`` is duplicated and the
value of the last key overwrites the previous one.

Extensions
----------

`python-benedict <https://github.com/fabiocaccamo/python-benedict>`_
``dict`` subclass with keylist/keypath/keyattr support and I/O shortcuts.
:doc:`pandas <Python4DataScience:workspace/pandas/python-data-structures>`
can convert Dicts into Series and DataFrames.
can convert dicts into series and DataFrames.

Checks
------

* Suppose you have the two dictionaries ``x = {"a":1, "b":2, "c":3, "d":4}`` and
``y = {"a":5, "e":6, "f":7}``. What would be the content of ``x`` after the
following code snippets have been executed?
* Suppose you have the two dictionaries ``x = {"a": 1, "b": 2, "c": 3, "d": 4}``
and ``y = {"a": 5, "e": 6, "f": 7}``. What would be the content of ``x`` after
the following code snippets have been executed?

.. code-block:: pycon
>>> del x["b"]
>>> z = x.setdefault("e", 8)
>>> x.update(y)
.. code-block:: pycon
>>> x = {"a": 1, "b": 2, "c": 3, "d": 4}
>>> y = {"a": 5, "e": 6, "f": 7}
>>> del x["b"]
>>> z = x.setdefault("e", 8)
>>> x.update(y)
>>> x
{'a': 5, 'c': 3, 'd': 4, 'e': 6, 'f': 7}
* Which of the following expressions can be a key of a dictionary: ``1``;
``"Veit"``; ``("Veit", [1])``; ``[("Veit", [1])]``; ``["Veit"]``; ``("Veit",
"Tim", "Monique")``

.. code-block:: pycon
>>> d = {}
>>> d[1] = None
>>> d["Veit"] = None
>>> d[("Veit", [1])]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d[["Veit"]] = None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> d[("Veit", "Tim", "Monique")] = None
* You can use a :doc:`Dictionary </types/dicts>` like a spreadsheet table by
using :doc:`/types/sequences-sets/tuples` as key row and column values. Write
sample code to add and retrieve values.

.. code-block:: pycon
* Which of the following expressions can be a key of a dictionary?
``1``; ``"Veit"``; ``("Veit", [1])``; ``[("Veit", [1])]``; ``["Veit"]``;
``("Veit", "Tim", "Monique")``

>>> sheet = {}
>>> sheet[("A", 0)] = 1
>>> sheet[("A", 1)] = 2
>>> sheet[("B", 0)] = 3
>>> sheet[("B", 1)] = 4
>>> print(sheet[("A", 1)])
2
* You can use a :doc:`dictionary </types/dicts>` and use it like a spreadsheet
sheet by using :doc:`tuples </types/sequences-sets/tuples>` as key row and
column values. Write sample code to add and retrieve values.

0 comments on commit 5b8c0d2

Please sign in to comment.