Dictionary Objects¶
- PyTypeObjectPyDict_Type¶
- Part of theStable ABI.
This instance of
PyTypeObjectrepresents the Python dictionarytype. This is the same object asdictin the Python layer.
- intPyDict_Check(PyObject*p)¶
Return true ifp is a dict object or an instance of a subtype of the dicttype. This function always succeeds.
- intPyDict_CheckExact(PyObject*p)¶
Return true ifp is a dict object, but not an instance of a subtype ofthe dict type. This function always succeeds.
- PyObject*PyDict_New()¶
- Return value: New reference. Part of theStable ABI.
Return a new empty dictionary, or
NULLon failure.
- PyObject*PyDictProxy_New(PyObject*mapping)¶
- Return value: New reference. Part of theStable ABI.
Return a
types.MappingProxyTypeobject for a mapping whichenforces read-only behavior. This is normally used to create a view toprevent modification of the dictionary for non-dynamic class types.
- voidPyDict_Clear(PyObject*p)¶
- Part of theStable ABI.
Empty an existing dictionary of all key-value pairs.
- intPyDict_Contains(PyObject*p,PyObject*key)¶
- Part of theStable ABI.
Determine if dictionaryp containskey. If an item inp matcheskey, return
1, otherwise return0. On error, return-1.This is equivalent to the Python expressionkeyinp.
- intPyDict_ContainsString(PyObject*p,constchar*key)¶
This is the same as
PyDict_Contains(), butkey is specified as aconstchar* UTF-8 encoded bytes string, rather than aPyObject*.Added in version 3.13.
- PyObject*PyDict_Copy(PyObject*p)¶
- Return value: New reference. Part of theStable ABI.
Return a new dictionary that contains the same key-value pairs asp.
- intPyDict_SetItem(PyObject*p,PyObject*key,PyObject*val)¶
- Part of theStable ABI.
Insertval into the dictionaryp with a key ofkey.key must behashable; if it isn’t,
TypeErrorwill be raised. Return0on success or-1on failure. This functiondoes not steal areference toval.
- intPyDict_SetItemString(PyObject*p,constchar*key,PyObject*val)¶
- Part of theStable ABI.
This is the same as
PyDict_SetItem(), butkey isspecified as aconstchar* UTF-8 encoded bytes string,rather than aPyObject*.
- intPyDict_DelItem(PyObject*p,PyObject*key)¶
- Part of theStable ABI.
Remove the entry in dictionaryp with keykey.key must behashable;if it isn’t,
TypeErroris raised.Ifkey is not in the dictionary,KeyErroris raised.Return0on success or-1on failure.
- intPyDict_DelItemString(PyObject*p,constchar*key)¶
- Part of theStable ABI.
This is the same as
PyDict_DelItem(), butkey isspecified as aconstchar* UTF-8 encoded bytes string,rather than aPyObject*.
- intPyDict_GetItemRef(PyObject*p,PyObject*key,PyObject**result)¶
- Part of theStable ABI since version 3.13.
Return a newstrong reference to the object from dictionarypwhich has a keykey:
If the key is present, set*result to a newstrong referenceto the value and return
1.If the key is missing, set*result to
NULLand return0.On error, raise an exception and return
-1.
Added in version 3.13.
See also the
PyObject_GetItem()function.
- PyObject*PyDict_GetItem(PyObject*p,PyObject*key)¶
- Return value: Borrowed reference. Part of theStable ABI.
Return aborrowed reference to the object from dictionaryp whichhas a keykey. Return
NULLif the keykey is missingwithoutsetting an exception.Note
Exceptions that occur while this calls
__hash__()and__eq__()methods are silently ignored.Prefer thePyDict_GetItemWithError()function instead.Changed in version 3.10:Calling this API without anattached thread state had been allowed for historicalreason. It is no longer allowed.
- PyObject*PyDict_GetItemWithError(PyObject*p,PyObject*key)¶
- Return value: Borrowed reference. Part of theStable ABI.
Variant of
PyDict_GetItem()that does not suppressexceptions. ReturnNULLwith an exception set if an exceptionoccurred. ReturnNULLwithout an exception set if the keywasn’t present.
- PyObject*PyDict_GetItemString(PyObject*p,constchar*key)¶
- Return value: Borrowed reference. Part of theStable ABI.
This is the same as
PyDict_GetItem(), butkey is specified as aconstchar* UTF-8 encoded bytes string, rather than aPyObject*.Note
Exceptions that occur while this calls
__hash__()and__eq__()methods or while creating the temporarystrobject are silently ignored.Prefer using thePyDict_GetItemWithError()function with your ownPyUnicode_FromString()key instead.
- intPyDict_GetItemStringRef(PyObject*p,constchar*key,PyObject**result)¶
- Part of theStable ABI since version 3.13.
Similar to
PyDict_GetItemRef(), butkey is specified as aconstchar* UTF-8 encoded bytes string, rather than aPyObject*.Added in version 3.13.
- PyObject*PyDict_SetDefault(PyObject*p,PyObject*key,PyObject*defaultobj)¶
- Return value: Borrowed reference.
This is the same as the Python-level
dict.setdefault(). If present, itreturns the value corresponding tokey from the dictionaryp. If the keyis not in the dict, it is inserted with valuedefaultobj anddefaultobjis returned. This function evaluates the hash function ofkey only once,instead of evaluating it independently for the lookup and the insertion.Added in version 3.4.
- intPyDict_SetDefaultRef(PyObject*p,PyObject*key,PyObject*default_value,PyObject**result)¶
Insertsdefault_value into the dictionaryp with a key ofkey if thekey is not already present in the dictionary. Ifresult is not
NULL,then*result is set to astrong reference to eitherdefault_value, if the key was not present, or the existing value, ifkeywas already present in the dictionary.Returns1if the key was present anddefault_value was not inserted,or0if the key was not present anddefault_value was inserted.On failure, returns-1, sets an exception, and sets*resulttoNULL.For clarity: if you have a strong reference todefault_value beforecalling this function, then after it returns, you hold a strong referenceto bothdefault_value and*result (if it’s not
NULL).These may refer to the same object: in that case you hold two separatereferences to it.Added in version 3.13.
- intPyDict_Pop(PyObject*p,PyObject*key,PyObject**result)¶
Removekey from dictionaryp and optionally return the removed value.Do not raise
KeyErrorif the key is missing.If the key is present, set*result to a new reference to the removedvalue ifresult is not
NULL, and return1.If the key is missing, set*result to
NULLifresult is notNULL, and return0.On error, raise an exception and return
-1.
Similar to
dict.pop(), but without the default value andnot raisingKeyErrorif the key is missing.Added in version 3.13.
- intPyDict_PopString(PyObject*p,constchar*key,PyObject**result)¶
Similar to
PyDict_Pop(), butkey is specified as aconstchar* UTF-8 encoded bytes string, rather than aPyObject*.Added in version 3.13.
- PyObject*PyDict_Items(PyObject*p)¶
- Return value: New reference. Part of theStable ABI.
Return a
PyListObjectcontaining all the items from the dictionary.
- PyObject*PyDict_Keys(PyObject*p)¶
- Return value: New reference. Part of theStable ABI.
Return a
PyListObjectcontaining all the keys from the dictionary.
- PyObject*PyDict_Values(PyObject*p)¶
- Return value: New reference. Part of theStable ABI.
Return a
PyListObjectcontaining all the values from the dictionaryp.
- Py_ssize_tPyDict_Size(PyObject*p)¶
- Part of theStable ABI.
Return the number of items in the dictionary. This is equivalent to
len(p)on a dictionary.
- Py_ssize_tPyDict_GET_SIZE(PyObject*p)¶
Similar to
PyDict_Size(), but without error checking.
- intPyDict_Next(PyObject*p,Py_ssize_t*ppos,PyObject**pkey,PyObject**pvalue)¶
- Part of theStable ABI.
Iterate over all key-value pairs in the dictionaryp. The
Py_ssize_treferred to byppos must be initialized to0prior to the first call to this function to start the iteration; thefunction returns true for each pair in the dictionary, and false once allpairs have been reported. The parameterspkey andpvalue should eitherpoint toPyObject* variables that will be filled in with each keyand value, respectively, or may beNULL. Any references returned throughthem are borrowed.ppos should not be altered during iteration. Itsvalue represents offsets within the internal dictionary structure, andsince the structure is sparse, the offsets are not consecutive.For example:
PyObject*key,*value;Py_ssize_tpos=0;while(PyDict_Next(self->dict,&pos,&key,&value)){/* do something interesting with the values... */...}
The dictionaryp should not be mutated during iteration. It is safe tomodify the values of the keys as you iterate over the dictionary, but onlyso long as the set of keys does not change. For example:
PyObject*key,*value;Py_ssize_tpos=0;while(PyDict_Next(self->dict,&pos,&key,&value)){longi=PyLong_AsLong(value);if(i==-1&&PyErr_Occurred()){return-1;}PyObject*o=PyLong_FromLong(i+1);if(o==NULL)return-1;if(PyDict_SetItem(self->dict,key,o)<0){Py_DECREF(o);return-1;}Py_DECREF(o);}
The function is not thread-safe in thefree-threadedbuild without external synchronization. You can use
Py_BEGIN_CRITICAL_SECTIONto lock the dictionary while iteratingover it:Py_BEGIN_CRITICAL_SECTION(self->dict);while(PyDict_Next(self->dict,&pos,&key,&value)){...}Py_END_CRITICAL_SECTION();
Note
On the free-threaded build, this function can be used safely inside acritical section. However, the references returned forpkey andpvalueareborrowed and are only valid while thecritical section is held. If you need to use these objects outside thecritical section or when the critical section can be suspended, create astrong reference (for example, using
Py_NewRef()).
- intPyDict_Merge(PyObject*a,PyObject*b,intoverride)¶
- Part of theStable ABI.
Iterate over mapping objectb adding key-value pairs to dictionarya.b may be a dictionary, or any object supporting
PyMapping_Keys()andPyObject_GetItem(). Ifoverride is true, existing pairs inawill be replaced if a matching key is found inb, otherwise pairs willonly be added if there is not a matching key ina. Return0onsuccess or-1if an exception was raised.
- intPyDict_Update(PyObject*a,PyObject*b)¶
- Part of theStable ABI.
This is the same as
PyDict_Merge(a,b,1)in C, and is similar toa.update(b)in Python except thatPyDict_Update()doesn’t fallback to the iterating over a sequence of key value pairs if the secondargument has no “keys” attribute. Return0on success or-1if anexception was raised.
- intPyDict_MergeFromSeq2(PyObject*a,PyObject*seq2,intoverride)¶
- Part of theStable ABI.
Update or merge into dictionarya, from the key-value pairs inseq2.seq2 must be an iterable object producing iterable objects of length 2,viewed as key-value pairs. In case of duplicate keys, the last wins ifoverride is true, else the first wins. Return
0on success or-1if an exception was raised. Equivalent Python (except for the returnvalue):defPyDict_MergeFromSeq2(a,seq2,override):forkey,valueinseq2:ifoverrideorkeynotina:a[key]=value
- intPyDict_AddWatcher(PyDict_WatchCallbackcallback)¶
Registercallback as a dictionary watcher. Return a non-negative integerid which must be passed to future calls to
PyDict_Watch(). In caseof error (e.g. no more watcher IDs available), return-1and set anexception.Added in version 3.12.
- intPyDict_ClearWatcher(intwatcher_id)¶
Clear watcher identified bywatcher_id previously returned from
PyDict_AddWatcher(). Return0on success,-1on error (e.g.if the givenwatcher_id was never registered.)Added in version 3.12.
- intPyDict_Watch(intwatcher_id,PyObject*dict)¶
Mark dictionarydict as watched. The callback grantedwatcher_id by
PyDict_AddWatcher()will be called whendict is modified ordeallocated. Return0on success or-1on error.Added in version 3.12.
- intPyDict_Unwatch(intwatcher_id,PyObject*dict)¶
Mark dictionarydict as no longer watched. The callback grantedwatcher_id by
PyDict_AddWatcher()will no longer be called whendict is modified or deallocated. The dict must previously have beenwatched by this watcher. Return0on success or-1on error.Added in version 3.12.
- typePyDict_WatchEvent¶
Enumeration of possible dictionary watcher events:
PyDict_EVENT_ADDED,PyDict_EVENT_MODIFIED,PyDict_EVENT_DELETED,PyDict_EVENT_CLONED,PyDict_EVENT_CLEARED, orPyDict_EVENT_DEALLOCATED.Added in version 3.12.
- typedefint(*PyDict_WatchCallback)(PyDict_WatchEventevent,PyObject*dict,PyObject*key,PyObject*new_value)¶
Type of a dict watcher callback function.
Ifevent is
PyDict_EVENT_CLEAREDorPyDict_EVENT_DEALLOCATED, bothkey andnew_value will beNULL. Ifevent isPyDict_EVENT_ADDEDorPyDict_EVENT_MODIFIED,new_value will be the new value forkey.Ifevent isPyDict_EVENT_DELETED,key is being deleted from thedictionary andnew_value will beNULL.PyDict_EVENT_CLONEDoccurs whendict was previously empty and anotherdict is merged into it. To maintain efficiency of this operation, per-keyPyDict_EVENT_ADDEDevents are not issued in this case; instead asinglePyDict_EVENT_CLONEDis issued, andkey will be the sourcedictionary.The callback may inspect but must not modifydict; doing so could haveunpredictable effects, including infinite recursion. Do not trigger Pythoncode execution in the callback, as it could modify the dict as a side effect.
Ifevent is
PyDict_EVENT_DEALLOCATED, taking a new reference in thecallback to the about-to-be-destroyed dictionary will resurrect it andprevent it from being freed at this time. When the resurrected object isdestroyed later, any watcher callbacks active at that time will be calledagain.Callbacks occur before the notified modification todict takes place, sothe prior state ofdict can be inspected.
If the callback sets an exception, it must return
-1; this exception willbe printed as an unraisable exception usingPyErr_WriteUnraisable().Otherwise it should return0.There may already be a pending exception set on entry to the callback. Inthis case, the callback should return
0with the same exception stillset. This means the callback may not call any other API that can set anexception unless it saves and clears the exception state first, and restoresit before returning.Added in version 3.12.
Dictionary View Objects¶
- intPyDictViewSet_Check(PyObject*op)¶
Return true ifop is a view of a set inside a dictionary. This is currentlyequivalent toPyDictKeys_Check(op)||PyDictItems_Check(op). Thisfunction always succeeds.
- PyTypeObjectPyDictKeys_Type¶
- Part of theStable ABI.
Type object for a view of dictionary keys. In Python, this is the type ofthe object returned by
dict.keys().
- intPyDictKeys_Check(PyObject*op)¶
Return true ifop is an instance of a dictionary keys view. This functionalways succeeds.
- PyTypeObjectPyDictValues_Type¶
- Part of theStable ABI.
Type object for a view of dictionary values. In Python, this is the type ofthe object returned by
dict.values().
- intPyDictValues_Check(PyObject*op)¶
Return true ifop is an instance of a dictionary values view. This functionalways succeeds.
- PyTypeObjectPyDictItems_Type¶
- Part of theStable ABI.
Type object for a view of dictionary items. In Python, this is the type ofthe object returned by
dict.items().
Ordered Dictionaries¶
Python’s C API provides interface forcollections.OrderedDict from C.Since Python 3.7, dictionaries are ordered by default, so there is usuallylittle need for these functions; preferPyDict* where possible.
- PyTypeObjectPyODict_Type¶
Type object for ordered dictionaries. This is the same object as
collections.OrderedDictin the Python layer.
- intPyODict_Check(PyObject*od)¶
Return true ifod is an ordered dictionary object or an instance of asubtype of the
OrderedDicttype. This functionalways succeeds.
- intPyODict_CheckExact(PyObject*od)¶
Return true ifod is an ordered dictionary object, but not an instance ofa subtype of the
OrderedDicttype.This function always succeeds.
- PyTypeObjectPyODictKeys_Type¶
Analogous to
PyDictKeys_Typefor ordered dictionaries.
- PyTypeObjectPyODictValues_Type¶
Analogous to
PyDictValues_Typefor ordered dictionaries.
- PyTypeObjectPyODictItems_Type¶
Analogous to
PyDictItems_Typefor ordered dictionaries.
- PyObject*PyODict_New(void)¶
Return a new empty ordered dictionary, or
NULLon failure.This is analogous to
PyDict_New().
- intPyODict_SetItem(PyObject*od,PyObject*key,PyObject*value)¶
Insertvalue into the ordered dictionaryod with a key ofkey.Return
0on success or-1with an exception set on failure.This is analogous to
PyDict_SetItem().
- intPyODict_DelItem(PyObject*od,PyObject*key)¶
Remove the entry in the ordered dictionaryod with keykey.Return
0on success or-1with an exception set on failure.This is analogous to
PyDict_DelItem().
These aresoft deprecated aliases toPyDict APIs:
|
|
|---|---|
| |
| |
| |
| |
| |
|