• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1.. highlight:: c
2
3.. _dictobjects:
4
5Dictionary Objects
6------------------
7
8.. index:: pair: object; dictionary
9
10
11.. c:type:: PyDictObject
12
13   This subtype of :c:type:`PyObject` represents a Python dictionary object.
14
15
16.. c:var:: PyTypeObject PyDict_Type
17
18   This instance of :c:type:`PyTypeObject` represents the Python dictionary
19   type.  This is the same object as :class:`dict` in the Python layer.
20
21
22.. c:function:: int PyDict_Check(PyObject *p)
23
24   Return true if *p* is a dict object or an instance of a subtype of the dict
25   type.  This function always succeeds.
26
27
28.. c:function:: int PyDict_CheckExact(PyObject *p)
29
30   Return true if *p* is a dict object, but not an instance of a subtype of
31   the dict type.  This function always succeeds.
32
33
34.. c:function:: PyObject* PyDict_New()
35
36   Return a new empty dictionary, or ``NULL`` on failure.
37
38
39.. c:function:: PyObject* PyDictProxy_New(PyObject *mapping)
40
41   Return a :class:`types.MappingProxyType` object for a mapping which
42   enforces read-only behavior.  This is normally used to create a view to
43   prevent modification of the dictionary for non-dynamic class types.
44
45
46.. c:function:: void PyDict_Clear(PyObject *p)
47
48   Empty an existing dictionary of all key-value pairs.
49
50
51.. c:function:: int PyDict_Contains(PyObject *p, PyObject *key)
52
53   Determine if dictionary *p* contains *key*.  If an item in *p* is matches
54   *key*, return ``1``, otherwise return ``0``.  On error, return ``-1``.
55   This is equivalent to the Python expression ``key in p``.
56
57
58.. c:function:: int PyDict_ContainsString(PyObject *p, const char *key)
59
60   This is the same as :c:func:`PyDict_Contains`, but *key* is specified as a
61   :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
62   :c:expr:`PyObject*`.
63
64   .. versionadded:: 3.13
65
66
67.. c:function:: PyObject* PyDict_Copy(PyObject *p)
68
69   Return a new dictionary that contains the same key-value pairs as *p*.
70
71
72.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
73
74   Insert *val* into the dictionary *p* with a key of *key*.  *key* must be
75   :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return
76   ``0`` on success or ``-1`` on failure.  This function *does not* steal a
77   reference to *val*.
78
79
80.. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
81
82   This is the same as :c:func:`PyDict_SetItem`, but *key* is
83   specified as a :c:expr:`const char*` UTF-8 encoded bytes string,
84   rather than a :c:expr:`PyObject*`.
85
86
87.. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key)
88
89   Remove the entry in dictionary *p* with key *key*. *key* must be :term:`hashable`;
90   if it isn't, :exc:`TypeError` is raised.
91   If *key* is not in the dictionary, :exc:`KeyError` is raised.
92   Return ``0`` on success or ``-1`` on failure.
93
94
95.. c:function:: int PyDict_DelItemString(PyObject *p, const char *key)
96
97   This is the same as :c:func:`PyDict_DelItem`, but *key* is
98   specified as a :c:expr:`const char*` UTF-8 encoded bytes string,
99   rather than a :c:expr:`PyObject*`.
100
101
102.. c:function:: int PyDict_GetItemRef(PyObject *p, PyObject *key, PyObject **result)
103
104   Return a new :term:`strong reference` to the object from dictionary *p*
105   which has a key *key*:
106
107   * If the key is present, set *\*result* to a new :term:`strong reference`
108     to the value and return ``1``.
109   * If the key is missing, set *\*result* to ``NULL`` and return ``0``.
110   * On error, raise an exception and return ``-1``.
111
112   .. versionadded:: 3.13
113
114   See also the :c:func:`PyObject_GetItem` function.
115
116
117.. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
118
119   Return a :term:`borrowed reference` to the object from dictionary *p* which
120   has a key *key*.  Return ``NULL`` if the key *key* is missing *without*
121   setting an exception.
122
123   .. note::
124
125      Exceptions that occur while this calls :meth:`~object.__hash__` and
126      :meth:`~object.__eq__` methods are silently ignored.
127      Prefer the :c:func:`PyDict_GetItemWithError` function instead.
128
129   .. versionchanged:: 3.10
130      Calling this API without :term:`GIL` held had been allowed for historical
131      reason. It is no longer allowed.
132
133
134.. c:function:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)
135
136   Variant of :c:func:`PyDict_GetItem` that does not suppress
137   exceptions. Return ``NULL`` **with** an exception set if an exception
138   occurred.  Return ``NULL`` **without** an exception set if the key
139   wasn't present.
140
141
142.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
143
144   This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a
145   :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
146   :c:expr:`PyObject*`.
147
148   .. note::
149
150      Exceptions that occur while this calls :meth:`~object.__hash__` and
151      :meth:`~object.__eq__` methods or while creating the temporary :class:`str`
152      object are silently ignored.
153      Prefer using the :c:func:`PyDict_GetItemWithError` function with your own
154      :c:func:`PyUnicode_FromString` *key* instead.
155
156
157.. c:function:: int PyDict_GetItemStringRef(PyObject *p, const char *key, PyObject **result)
158
159   Similar than :c:func:`PyDict_GetItemRef`, but *key* is specified as a
160   :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
161   :c:expr:`PyObject*`.
162
163   .. versionadded:: 3.13
164
165
166.. c:function:: PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
167
168   This is the same as the Python-level :meth:`dict.setdefault`.  If present, it
169   returns the value corresponding to *key* from the dictionary *p*.  If the key
170   is not in the dict, it is inserted with value *defaultobj* and *defaultobj*
171   is returned.  This function evaluates the hash function of *key* only once,
172   instead of evaluating it independently for the lookup and the insertion.
173
174   .. versionadded:: 3.4
175
176
177.. c:function:: int PyDict_SetDefaultRef(PyObject *p, PyObject *key, PyObject *default_value, PyObject **result)
178
179   Inserts *default_value* into the dictionary *p* with a key of *key* if the
180   key is not already present in the dictionary. If *result* is not ``NULL``,
181   then *\*result* is set to a :term:`strong reference` to either
182   *default_value*, if the key was not present, or the existing value, if *key*
183   was already present in the dictionary.
184   Returns ``1`` if the key was present and *default_value* was not inserted,
185   or ``0`` if the key was not present and *default_value* was inserted.
186   On failure, returns ``-1``, sets an exception, and sets ``*result``
187   to ``NULL``.
188
189   For clarity: if you have a strong reference to *default_value* before
190   calling this function, then after it returns, you hold a strong reference
191   to both *default_value* and *\*result* (if it's not ``NULL``).
192   These may refer to the same object: in that case you hold two separate
193   references to it.
194
195   .. versionadded:: 3.13
196
197
198.. c:function:: int PyDict_Pop(PyObject *p, PyObject *key, PyObject **result)
199
200   Remove *key* from dictionary *p* and optionally return the removed value.
201   Do not raise :exc:`KeyError` if the key missing.
202
203   - If the key is present, set *\*result* to a new reference to the removed
204     value if *result* is not ``NULL``, and return ``1``.
205   - If the key is missing, set *\*result* to ``NULL`` if *result* is not
206     ``NULL``, and return ``0``.
207   - On error, raise an exception and return ``-1``.
208
209   This is similar to :meth:`dict.pop`, but without the default value and
210   not raising :exc:`KeyError` if the key missing.
211
212   .. versionadded:: 3.13
213
214
215.. c:function:: int PyDict_PopString(PyObject *p, const char *key, PyObject **result)
216
217   Similar to :c:func:`PyDict_Pop`, but *key* is specified as a
218   :c:expr:`const char*` UTF-8 encoded bytes string, rather than a
219   :c:expr:`PyObject*`.
220
221   .. versionadded:: 3.13
222
223
224.. c:function:: PyObject* PyDict_Items(PyObject *p)
225
226   Return a :c:type:`PyListObject` containing all the items from the dictionary.
227
228
229.. c:function:: PyObject* PyDict_Keys(PyObject *p)
230
231   Return a :c:type:`PyListObject` containing all the keys from the dictionary.
232
233
234.. c:function:: PyObject* PyDict_Values(PyObject *p)
235
236   Return a :c:type:`PyListObject` containing all the values from the dictionary
237   *p*.
238
239
240.. c:function:: Py_ssize_t PyDict_Size(PyObject *p)
241
242   .. index:: pair: built-in function; len
243
244   Return the number of items in the dictionary.  This is equivalent to
245   ``len(p)`` on a dictionary.
246
247
248.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
249
250   Iterate over all key-value pairs in the dictionary *p*.  The
251   :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0``
252   prior to the first call to this function to start the iteration; the
253   function returns true for each pair in the dictionary, and false once all
254   pairs have been reported.  The parameters *pkey* and *pvalue* should either
255   point to :c:expr:`PyObject*` variables that will be filled in with each key
256   and value, respectively, or may be ``NULL``.  Any references returned through
257   them are borrowed.  *ppos* should not be altered during iteration. Its
258   value represents offsets within the internal dictionary structure, and
259   since the structure is sparse, the offsets are not consecutive.
260
261   For example::
262
263      PyObject *key, *value;
264      Py_ssize_t pos = 0;
265
266      while (PyDict_Next(self->dict, &pos, &key, &value)) {
267          /* do something interesting with the values... */
268          ...
269      }
270
271   The dictionary *p* should not be mutated during iteration.  It is safe to
272   modify the values of the keys as you iterate over the dictionary, but only
273   so long as the set of keys does not change.  For example::
274
275      PyObject *key, *value;
276      Py_ssize_t pos = 0;
277
278      while (PyDict_Next(self->dict, &pos, &key, &value)) {
279          long i = PyLong_AsLong(value);
280          if (i == -1 && PyErr_Occurred()) {
281              return -1;
282          }
283          PyObject *o = PyLong_FromLong(i + 1);
284          if (o == NULL)
285              return -1;
286          if (PyDict_SetItem(self->dict, key, o) < 0) {
287              Py_DECREF(o);
288              return -1;
289          }
290          Py_DECREF(o);
291      }
292
293   The function is not thread-safe in the :term:`free-threaded <free threading>`
294   build without external synchronization.  You can use
295   :c:macro:`Py_BEGIN_CRITICAL_SECTION` to lock the dictionary while iterating
296   over it::
297
298      Py_BEGIN_CRITICAL_SECTION(self->dict);
299      while (PyDict_Next(self->dict, &pos, &key, &value)) {
300          ...
301      }
302      Py_END_CRITICAL_SECTION();
303
304
305.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
306
307   Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
308   *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys`
309   and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
310   will be replaced if a matching key is found in *b*, otherwise pairs will
311   only be added if there is not a matching key in *a*. Return ``0`` on
312   success or ``-1`` if an exception was raised.
313
314
315.. c:function:: int PyDict_Update(PyObject *a, PyObject *b)
316
317   This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to
318   ``a.update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall
319   back to the iterating over a sequence of key value pairs if the second
320   argument has no "keys" attribute.  Return ``0`` on success or ``-1`` if an
321   exception was raised.
322
323
324.. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
325
326   Update or merge into dictionary *a*, from the key-value pairs in *seq2*.
327   *seq2* must be an iterable object producing iterable objects of length 2,
328   viewed as key-value pairs.  In case of duplicate keys, the last wins if
329   *override* is true, else the first wins. Return ``0`` on success or ``-1``
330   if an exception was raised. Equivalent Python (except for the return
331   value)::
332
333      def PyDict_MergeFromSeq2(a, seq2, override):
334          for key, value in seq2:
335              if override or key not in a:
336                  a[key] = value
337
338.. c:function:: int PyDict_AddWatcher(PyDict_WatchCallback callback)
339
340   Register *callback* as a dictionary watcher. Return a non-negative integer
341   id which must be passed to future calls to :c:func:`PyDict_Watch`. In case
342   of error (e.g. no more watcher IDs available), return ``-1`` and set an
343   exception.
344
345   .. versionadded:: 3.12
346
347.. c:function:: int PyDict_ClearWatcher(int watcher_id)
348
349   Clear watcher identified by *watcher_id* previously returned from
350   :c:func:`PyDict_AddWatcher`. Return ``0`` on success, ``-1`` on error (e.g.
351   if the given *watcher_id* was never registered.)
352
353   .. versionadded:: 3.12
354
355.. c:function:: int PyDict_Watch(int watcher_id, PyObject *dict)
356
357   Mark dictionary *dict* as watched. The callback granted *watcher_id* by
358   :c:func:`PyDict_AddWatcher` will be called when *dict* is modified or
359   deallocated. Return ``0`` on success or ``-1`` on error.
360
361   .. versionadded:: 3.12
362
363.. c:function:: int PyDict_Unwatch(int watcher_id, PyObject *dict)
364
365   Mark dictionary *dict* as no longer watched. The callback granted
366   *watcher_id* by :c:func:`PyDict_AddWatcher` will no longer be called when
367   *dict* is modified or deallocated. The dict must previously have been
368   watched by this watcher. Return ``0`` on success or ``-1`` on error.
369
370   .. versionadded:: 3.12
371
372.. c:type:: PyDict_WatchEvent
373
374   Enumeration of possible dictionary watcher events: ``PyDict_EVENT_ADDED``,
375   ``PyDict_EVENT_MODIFIED``, ``PyDict_EVENT_DELETED``, ``PyDict_EVENT_CLONED``,
376   ``PyDict_EVENT_CLEARED``, or ``PyDict_EVENT_DEALLOCATED``.
377
378   .. versionadded:: 3.12
379
380.. c:type:: int (*PyDict_WatchCallback)(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject *new_value)
381
382   Type of a dict watcher callback function.
383
384   If *event* is ``PyDict_EVENT_CLEARED`` or ``PyDict_EVENT_DEALLOCATED``, both
385   *key* and *new_value* will be ``NULL``. If *event* is ``PyDict_EVENT_ADDED``
386   or ``PyDict_EVENT_MODIFIED``, *new_value* will be the new value for *key*.
387   If *event* is ``PyDict_EVENT_DELETED``, *key* is being deleted from the
388   dictionary and *new_value* will be ``NULL``.
389
390   ``PyDict_EVENT_CLONED`` occurs when *dict* was previously empty and another
391   dict is merged into it. To maintain efficiency of this operation, per-key
392   ``PyDict_EVENT_ADDED`` events are not issued in this case; instead a
393   single ``PyDict_EVENT_CLONED`` is issued, and *key* will be the source
394   dictionary.
395
396   The callback may inspect but must not modify *dict*; doing so could have
397   unpredictable effects, including infinite recursion. Do not trigger Python
398   code execution in the callback, as it could modify the dict as a side effect.
399
400   If *event* is ``PyDict_EVENT_DEALLOCATED``, taking a new reference in the
401   callback to the about-to-be-destroyed dictionary will resurrect it and
402   prevent it from being freed at this time. When the resurrected object is
403   destroyed later, any watcher callbacks active at that time will be called
404   again.
405
406   Callbacks occur before the notified modification to *dict* takes place, so
407   the prior state of *dict* can be inspected.
408
409   If the callback sets an exception, it must return ``-1``; this exception will
410   be printed as an unraisable exception using :c:func:`PyErr_WriteUnraisable`.
411   Otherwise it should return ``0``.
412
413   There may already be a pending exception set on entry to the callback. In
414   this case, the callback should return ``0`` with the same exception still
415   set. This means the callback may not call any other API that can set an
416   exception unless it saves and clears the exception state first, and restores
417   it before returning.
418
419   .. versionadded:: 3.12
420