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