11Dictionaries
22============
33
4- Python’s built-in dictionary data type provides associative array functionality
5- implemented using hash tables. The built-in ``len `` function returns the number
6- of key-value pairs in a dictionary. The ``del `` statement can be used to delete
7- a key-value pair. As with :doc: `sequences-sets/lists ` , several dictionary
8- methods (:py:meth: `clear <dict.clear> `, :py:meth: `copy <dict.copy> `,
9- :py:meth: `get <dict.get> `, :py:meth: `items <dict.items> `, :py:meth: `keys
10- <dict.keys> `, :py:meth: `update <dict.update> ` and :py:meth: `values
11- <dict.values> `) are available.
12-
13- .. code-block :: pycon
14-
15- >>> x = {1: "eins", 2: "zwei"}
16- >>> x[3] = "drei"
17- >>> x["viertes"] = "vier"
18- >>> list(x.keys())
19- [1, 2, 3, 'viertes']
20- >>> x[1]
21- 'eins'
22- >>> x.get(1, "nicht vorhanden")
23- 'eins'
24- >>> x.get(5, "nicht vorhanden")
25- 'nicht vorhanden'
26-
27- Keys must be of immutable type, including :doc: `numbers/index `,
28- :doc: `strings/index ` and :doc: `sequences-sets/tuples `.
4+ Dictionaries consist of key-value pairs. Keys must be of invariant type,
5+ including numbers, :doc: `strings/index ` and :doc: `sequences-sets/tuples `.
296
307.. warning ::
318 Even if you can use different key types in a dictionary, you should avoid
32- this, as it not only makes it more difficult to read, but also sorting is
33- also made more difficult.
9+ doing so, as this not only makes it more difficult to read, but also to sort.
3410
3511Values can be any type of object, including mutable types such as
36- :doc: `sequences-sets/lists ` and :doc: `dicts `. If you try to access the value of
37- a key that is not in the dictionary, a ``KeyError `` exception is thrown. To
38- avoid this error, the dictionary method ``get `` optionally returns a custom
39- value if a key is not contained in a dictionary.
12+ :doc: `sequences-sets/lists ` and :doc: `dicts `.
13+
14+ .. code-block :: pycon
15+
16+ >>> dict = {
17+ ... "2022-01-31": -0.751442,
18+ ... "2022-02-01": 0.816935,
19+ ... "2022-02-02": -0.272546,
20+ ... }
21+ >>> dict["2022-02-03"] = -0.268295
22+
23+ If you try to access the value of a key that is not contained in the dictionary,
24+ a ``KeyError `` exception is thrown. To avoid this error, the dictionary method
25+ ``get `` optionally returns a user-defined value if a key is not contained in a
26+ dictionary.
27+
28+ .. code-block :: pycon
29+
30+ >>> dict["2022-02-03"]
31+ -0.268295
32+ >>> dict["2022-02-04"]
33+ Traceback (most recent call last):
34+ File "<python-input-15>", line 1, in <module>
35+ dict["2022-02-04"]
36+ ~~~~^^^^^^^^^^^^^^
37+ KeyError: '2022-02-04'
38+ >>> dict.get("2022-02-03", "Messwert nicht vorhanden")
39+ -0.268295
40+ >>> dict.get("2022-02-04", "Messwert nicht vorhanden")
41+ 'Messwert nicht vorhanden'
42+
43+ Other Dict methods
44+ ------------------
45+
46+ The :func: `len ` function built into Dicts returns the number of key-value pairs.
47+ The ``del `` statement can be used to delete a key-value pair. As with
48+ :doc: `sequences-sets/lists `, several dictionary methods ((:py:meth: `clear
49+ <dict.clear> `, :py:meth: `copy <dict.copy> `, :py:meth: `get <dict.get> `,
50+ :py:meth: `items <dict.items> `, :py:meth: `keys <dict.keys> `, :py:meth: `update
51+ <dict.update> ` and :py:meth: `values <dict.values> `) are available.
52+
53+ The :py:meth: `keys <dict.keys> `, :py:meth: `values <dict.values> ` and
54+ :py:meth: `items <dict.items> ` methods do not return lists, but dictionary view
55+ objects that behave like sequences, but are updated dynamically when the
56+ dictionary changes. For this reason, you must use the :func: `list ` function so
57+ that they become a list in these examples:
58+
59+ .. code-block :: pycon
60+
61+ >>> list(dict.keys())
62+ ['2022-01-31', '2022-02-01', '2022-02-02', '2022-02-03']
63+
64+ As of Python 3.6, dictionaries retain the order in which the keys were created,
65+ and they are also returned in this order with :py:meth: `keys <dict.keys> `.
66+
67+ Merging dictionaries
68+ ~~~~~~~~~~~~~~~~~~~~
69+
70+ You can use the :py:meth: `dict.update ` method to merge two dictionaries into a
71+ single dictionary:
72+
73+ .. code-block :: pycon
74+
75+ >>> titles = {7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}
76+ >>> new_titles = {7.0: "Data types", 7.3: "Sets"}
77+ >>> titles.update(new_titles)
78+ >>> titles
79+ {7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}
80+
81+ .. note ::
82+ The order of the operands is important, as ``7.0 `` is duplicated and the
83+ value of the last key overwrites the previous one.
4084
4185``setdefault ``
42- --------------
86+ ~~~~~~~~~~~~~~
4387
4488:py:meth: `setdefault <dict.setdefault> ` can be used to provide counters for the
4589keys of a dict, for example:
@@ -65,84 +109,31 @@ keys of a dict, for example:
65109 >>> collections.Counter(titles)
66110 Counter({'Lists': 2, 'Data types': 1, 'Sets': 1})
67111
68- Merging dictionaries
69- --------------------
70-
71- You can merge two dictionaries into a single dictionary using the
72- :py:meth: `dict.update ` method:
73-
74- .. code-block :: pycon
75-
76- >>> titles = {7.0: "Data Types", 7.1: "Lists", 7.2: "Tuples"}
77- >>> new_titles = {7.0: "Data types", 7.3: "Sets"}
78- >>> titles.update(new_titles)
79- >>> titles
80- {7.0: 'Data types', 7.1: 'Lists', 7.2: 'Tuples', 7.3: 'Sets'}
81-
82- .. note ::
83- The order of the operands is important, as ``7.0 `` is duplicated and the
84- value of the last key overwrites the previous one.
85-
86112 Extensions
87113----------
88114
89115`python-benedict <https://github.com/fabiocaccamo/python-benedict >`_
90116 ``dict `` subclass with keylist/keypath/keyattr support and I/O shortcuts.
91117:doc: `pandas <Python4DataScience:workspace/pandas/python-data-structures >`
92- can convert Dicts into Series and DataFrames.
118+ can convert dicts into series and DataFrames.
93119
94120Checks
95121------
96122
97- * Suppose you have the two dictionaries ``x = {"a":1, "b":2, "c":3, "d":4} `` and
98- ``y = {"a":5, "e":6, "f":7} ``. What would be the content of ``x `` after the
99- following code snippets have been executed?
123+ * Suppose you have the two dictionaries ``x = {"a": 1, "b": 2, "c": 3, "d": 4} ``
124+ and ``y = {"a": 5, "e": 6, "f": 7} ``. What would be the content of ``x `` after
125+ the following code snippets have been executed?
100126
101127 .. code-block :: pycon
102128
103129 >>> del x["b"]
104130 >>> z = x.setdefault("e", 8)
105131 >>> x.update(y)
106132
107- .. code-block :: pycon
108-
109- >>> x = {"a": 1, "b": 2, "c": 3, "d": 4}
110- >>> y = {"a": 5, "e": 6, "f": 7}
111- >>> del x["b"]
112- >>> z = x.setdefault("e", 8)
113- >>> x.update(y)
114- >>> x
115- {'a': 5, 'c': 3, 'd': 4, 'e': 6, 'f': 7}
116-
117- * Which of the following expressions can be a key of a dictionary: ``1 ``;
118- ``"Veit" ``; ``("Veit", [1]) ``; ``[("Veit", [1])] ``; ``["Veit"] ``; ``("Veit",
119- "Tim", "Monique") ``
120-
121- .. code-block :: pycon
122-
123- >>> d = {}
124- >>> d[1] = None
125- >>> d["Veit"] = None
126- >>> d[("Veit", [1])]
127- Traceback (most recent call last):
128- File "<stdin>", line 1, in <module>
129- TypeError: unhashable type: 'list'
130- >>> d[["Veit"]] = None
131- Traceback (most recent call last):
132- File "<stdin>", line 1, in <module>
133- TypeError: unhashable type: 'list'
134- >>> d[("Veit", "Tim", "Monique")] = None
135-
136- * You can use a :doc: `Dictionary </types/dicts >` like a spreadsheet table by
137- using :doc: `/types/sequences-sets/tuples ` as key row and column values. Write
138- sample code to add and retrieve values.
139-
140- .. code-block :: pycon
133+ * Which of the following expressions can be a key of a dictionary?
134+ ``1 ``; ``"Veit" ``; ``("Veit", [1]) ``; ``[("Veit", [1])] ``; ``["Veit"] ``;
135+ ``("Veit", "Tim", "Monique") ``
141136
142- >>> sheet = {}
143- >>> sheet[("A", 0)] = 1
144- >>> sheet[("A", 1)] = 2
145- >>> sheet[("B", 0)] = 3
146- >>> sheet[("B", 1)] = 4
147- >>> print(sheet[("A", 1)])
148- 2
137+ * You can use a :doc: `dictionary </types/dicts >` and use it like a spreadsheet
138+ sheet by using :doc: `tuples </types/sequences-sets/tuples >` as key row and
139+ column values. Write sample code to add and retrieve values.
0 commit comments