1.. highlight:: c
2
3.. _dictobjects:
4
5Dictionary Objects
6------------------
7
8.. index:: 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.
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.
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:: PyObject* PyDict_Copy(PyObject *p)
59
60   Return a new dictionary that contains the same key-value pairs as *p*.
61
62
63.. c:function:: int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
64
65   Insert *val* into the dictionary *p* with a key of *key*.  *key* must be
66   :term:`hashable`; if it isn't, :exc:`TypeError` will be raised. Return
67   ``0`` on success or ``-1`` on failure.  This function *does not* steal a
68   reference to *val*.
69
70
71.. c:function:: int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
72
73   .. index:: single: PyUnicode_FromString()
74
75   Insert *val* into the dictionary *p* using *key* as a key. *key* should
76   be a :c:type:`const char*`.  The key object is created using
77   ``PyUnicode_FromString(key)``.  Return ``0`` on success or ``-1`` on
78   failure.  This function *does not* steal a reference to *val*.
79
80
81.. c:function:: int PyDict_DelItem(PyObject *p, PyObject *key)
82
83   Remove the entry in dictionary *p* with key *key*. *key* must be hashable;
84   if it isn't, :exc:`TypeError` is raised.
85   If *key* is not in the dictionary, :exc:`KeyError` is raised.
86   Return ``0`` on success or ``-1`` on failure.
87
88
89.. c:function:: int PyDict_DelItemString(PyObject *p, const char *key)
90
91   Remove the entry in dictionary *p* which has a key specified by the string *key*.
92   If *key* is not in the dictionary, :exc:`KeyError` is raised.
93   Return ``0`` on success or ``-1`` on failure.
94
95
96.. c:function:: PyObject* PyDict_GetItem(PyObject *p, PyObject *key)
97
98   Return the object from dictionary *p* which has a key *key*.  Return ``NULL``
99   if the key *key* is not present, but *without* setting an exception.
100
101   Note that exceptions which occur while calling :meth:`__hash__` and
102   :meth:`__eq__` methods will get suppressed.
103   To get error reporting use :c:func:`PyDict_GetItemWithError()` instead.
104
105
106.. c:function:: PyObject* PyDict_GetItemWithError(PyObject *p, PyObject *key)
107
108   Variant of :c:func:`PyDict_GetItem` that does not suppress
109   exceptions. Return ``NULL`` **with** an exception set if an exception
110   occurred.  Return ``NULL`` **without** an exception set if the key
111   wasn't present.
112
113
114.. c:function:: PyObject* PyDict_GetItemString(PyObject *p, const char *key)
115
116   This is the same as :c:func:`PyDict_GetItem`, but *key* is specified as a
117   :c:type:`const char*`, rather than a :c:type:`PyObject*`.
118
119   Note that exceptions which occur while calling :meth:`__hash__` and
120   :meth:`__eq__` methods and creating a temporary string object
121   will get suppressed.
122   To get error reporting use :c:func:`PyDict_GetItemWithError()` instead.
123
124
125.. c:function:: PyObject* PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
126
127   This is the same as the Python-level :meth:`dict.setdefault`.  If present, it
128   returns the value corresponding to *key* from the dictionary *p*.  If the key
129   is not in the dict, it is inserted with value *defaultobj* and *defaultobj*
130   is returned.  This function evaluates the hash function of *key* only once,
131   instead of evaluating it independently for the lookup and the insertion.
132
133   .. versionadded:: 3.4
134
135.. c:function:: PyObject* PyDict_Items(PyObject *p)
136
137   Return a :c:type:`PyListObject` containing all the items from the dictionary.
138
139
140.. c:function:: PyObject* PyDict_Keys(PyObject *p)
141
142   Return a :c:type:`PyListObject` containing all the keys from the dictionary.
143
144
145.. c:function:: PyObject* PyDict_Values(PyObject *p)
146
147   Return a :c:type:`PyListObject` containing all the values from the dictionary
148   *p*.
149
150
151.. c:function:: Py_ssize_t PyDict_Size(PyObject *p)
152
153   .. index:: builtin: len
154
155   Return the number of items in the dictionary.  This is equivalent to
156   ``len(p)`` on a dictionary.
157
158
159.. c:function:: int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
160
161   Iterate over all key-value pairs in the dictionary *p*.  The
162   :c:type:`Py_ssize_t` referred to by *ppos* must be initialized to ``0``
163   prior to the first call to this function to start the iteration; the
164   function returns true for each pair in the dictionary, and false once all
165   pairs have been reported.  The parameters *pkey* and *pvalue* should either
166   point to :c:type:`PyObject*` variables that will be filled in with each key
167   and value, respectively, or may be ``NULL``.  Any references returned through
168   them are borrowed.  *ppos* should not be altered during iteration. Its
169   value represents offsets within the internal dictionary structure, and
170   since the structure is sparse, the offsets are not consecutive.
171
172   For example::
173
174      PyObject *key, *value;
175      Py_ssize_t pos = 0;
176
177      while (PyDict_Next(self->dict, &pos, &key, &value)) {
178          /* do something interesting with the values... */
179          ...
180      }
181
182   The dictionary *p* should not be mutated during iteration.  It is safe to
183   modify the values of the keys as you iterate over the dictionary, but only
184   so long as the set of keys does not change.  For example::
185
186      PyObject *key, *value;
187      Py_ssize_t pos = 0;
188
189      while (PyDict_Next(self->dict, &pos, &key, &value)) {
190          long i = PyLong_AsLong(value);
191          if (i == -1 && PyErr_Occurred()) {
192              return -1;
193          }
194          PyObject *o = PyLong_FromLong(i + 1);
195          if (o == NULL)
196              return -1;
197          if (PyDict_SetItem(self->dict, key, o) < 0) {
198              Py_DECREF(o);
199              return -1;
200          }
201          Py_DECREF(o);
202      }
203
204
205.. c:function:: int PyDict_Merge(PyObject *a, PyObject *b, int override)
206
207   Iterate over mapping object *b* adding key-value pairs to dictionary *a*.
208   *b* may be a dictionary, or any object supporting :c:func:`PyMapping_Keys`
209   and :c:func:`PyObject_GetItem`. If *override* is true, existing pairs in *a*
210   will be replaced if a matching key is found in *b*, otherwise pairs will
211   only be added if there is not a matching key in *a*. Return ``0`` on
212   success or ``-1`` if an exception was raised.
213
214
215.. c:function:: int PyDict_Update(PyObject *a, PyObject *b)
216
217   This is the same as ``PyDict_Merge(a, b, 1)`` in C, and is similar to
218   ``a.update(b)`` in Python except that :c:func:`PyDict_Update` doesn't fall
219   back to the iterating over a sequence of key value pairs if the second
220   argument has no "keys" attribute.  Return ``0`` on success or ``-1`` if an
221   exception was raised.
222
223
224.. c:function:: int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
225
226   Update or merge into dictionary *a*, from the key-value pairs in *seq2*.
227   *seq2* must be an iterable object producing iterable objects of length 2,
228   viewed as key-value pairs.  In case of duplicate keys, the last wins if
229   *override* is true, else the first wins. Return ``0`` on success or ``-1``
230   if an exception was raised. Equivalent Python (except for the return
231   value)::
232
233      def PyDict_MergeFromSeq2(a, seq2, override):
234          for key, value in seq2:
235              if override or key not in a:
236                  a[key] = value
237
238
239.. c:function:: int PyDict_ClearFreeList()
240
241   Clear the free list. Return the total number of freed items.
242
243   .. versionadded:: 3.3
244