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