Nota

¡Ayúdanos a traducir la documentación oficial de Python al Español! Puedes encontrar más información en Como contribuir. Ayuda a acercar Python a más personas de habla hispana.

Objetos diccionario

type PyDictObject

Este subtipo de PyObject representa un objeto diccionario de Python.

PyTypeObject PyDict_Type
Part of the Stable ABI.

Esta instancia de PyTypeObject representa el tipo diccionario de Python. Este es el mismo objeto que dict en la capa de Python.

int PyDict_Check(PyObject *p)

Retorna verdadero si p es un objeto dict o una instancia de un subtipo del tipo dict. Esta función siempre finaliza con éxito.

int PyDict_CheckExact(PyObject *p)

Retorna verdadero si p es un objeto dict, pero no una instancia de un subtipo del tipo dict. Esta función siempre finaliza con éxito.

PyObject *PyDict_New()
Return value: New reference. Part of the Stable ABI.

Retorna un nuevo diccionario vacío, o NULL en caso de falla.

PyObject *PyDictProxy_New(PyObject *mapping)
Return value: New reference. Part of the Stable ABI.

Retorna un objeto a types.MappingProxyType para una asignación que imponga un comportamiento de solo lectura. Esto normalmente se usa para crear una vista para evitar la modificación del diccionario para los tipos de clase no dinámicos.

void PyDict_Clear(PyObject *p)
Part of the Stable ABI.

Vacía un diccionario existente de todos los pares clave-valor (key-value).

int PyDict_Contains(PyObject *p, PyObject *key)
Part of the Stable ABI.

Determine si el diccionario p contiene key. Si un elemento en p coincide con la clave key, retorna 1; de lo contrario, retorna 0. En caso de error, retorna -1. Esto es equivalente a la expresión de Python key in p.

PyObject *PyDict_Copy(PyObject *p)
Return value: New reference. Part of the Stable ABI.

Retorna un nuevo diccionario que contiene los mismos pares clave-valor (key-value) que p.

int PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val)
Part of the Stable ABI.

Inserta val en el diccionario p con una clave key. key debe ser hashable; si no lo es, se lanzará TypeError. Retorna 0 en caso de éxito o -1 en caso de error. Esta función no roba una referencia a val.

int PyDict_SetItemString(PyObject *p, const char *key, PyObject *val)
Part of the Stable ABI.

Insert val into the dictionary p using key as a key. key should be a const char*. The key object is created using PyUnicode_FromString(key). Return 0 on success or -1 on failure. This function does not steal a reference to val.

int PyDict_DelItem(PyObject *p, PyObject *key)
Part of the Stable ABI.

Elimina la entrada en el diccionario p con la clave key. key debe ser hashable; si no lo es, se lanza TypeError. Si key no está en el diccionario, se lanza KeyError. Retorna 0 en caso de éxito o -1 en caso de error.

int PyDict_DelItemString(PyObject *p, const char *key)
Part of the Stable ABI.

Elimina la entrada en el diccionario p que tiene una clave especificada por la cadena de caracteres key. Si key no está en el diccionario, se lanza KeyError. Retorna 0 en caso de éxito o -1 en caso de error.

PyObject *PyDict_GetItem(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI.

Retorna el objeto del diccionario p que tiene una clave key. Retorna NULL si la clave key no está presente, pero sin lanzar una excepción.

Tenga en cuenta que las excepciones que se producen al llamar __hash__() y __eq__() se suprimirán los métodos. Para obtener informes de errores, utilice PyDict_GetItemWithError () en su lugar.

Distinto en la versión 3.10: Llamar a esta API sin retener el GIL había sido permitido por motivos históricos.Ya no está permitido.

PyObject *PyDict_GetItemWithError(PyObject *p, PyObject *key)
Return value: Borrowed reference. Part of the Stable ABI.

Variante de PyDict_GetItem() que no suprime las excepciones. Retorna NULL con una excepción establecida si se produjo una excepción. Retorna NULL sin una excepción establecida si la clave no estaba presente.

PyObject *PyDict_GetItemString(PyObject *p, const char *key)
Return value: Borrowed reference. Part of the Stable ABI.

This is the same as PyDict_GetItem(), but key is specified as a const char*, rather than a PyObject*.

Tenga en cuenta que las excepciones que se producen al llamar a __hash__() y __eq__() y al crear un objeto de cadena de caracteres temporal se suprimirán. Para obtener informes de errores, utilice PyDict_GetItemWithError() en su lugar.

PyObject *PyDict_SetDefault(PyObject *p, PyObject *key, PyObject *defaultobj)
Return value: Borrowed reference.

Esto es lo mismo al nivel de Python dict.setdefault(). Si está presente, retorna el valor correspondiente a key del diccionario p. Si la clave no está en el dict, se inserta con el valor defaultobj y se retorna defaultobj. Esta función evalúa la función hash de key solo una vez, en lugar de evaluarla independientemente para la búsqueda y la inserción.

Nuevo en la versión 3.4.

PyObject *PyDict_Items(PyObject *p)
Return value: New reference. Part of the Stable ABI.

Retorna un PyListObject que contiene todos los elementos del diccionario.

PyObject *PyDict_Keys(PyObject *p)
Return value: New reference. Part of the Stable ABI.

Retorna un PyListObject que contiene todas las claves del diccionario.

PyObject *PyDict_Values(PyObject *p)
Return value: New reference. Part of the Stable ABI.

Retorna un PyListObject que contiene todos los valores del diccionario p.

Py_ssize_t PyDict_Size(PyObject *p)
Part of the Stable ABI.

Retorna el número de elementos en el diccionario. Esto es equivalente a len(p) en un diccionario.

int PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
Part of the Stable ABI.

Iterate over all key-value pairs in the dictionary p. The Py_ssize_t referred to by ppos must be initialized to 0 prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false once all pairs have been reported. The parameters pkey and pvalue should either point to PyObject* variables that will be filled in with each key and value, respectively, or may be NULL. Any references returned through them are borrowed. ppos should not be altered during iteration. Its value represents offsets within the internal dictionary structure, and since the structure is sparse, the offsets are not consecutive.

Por ejemplo:

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {
    /* do something interesting with the values... */
    ...
}

El diccionario p no debe mutarse durante la iteración. Es seguro modificar los valores de las claves a medida que recorre el diccionario, pero solo mientras el conjunto de claves no cambie. Por ejemplo:

PyObject *key, *value;
Py_ssize_t pos = 0;

while (PyDict_Next(self->dict, &pos, &key, &value)) {
    long i = 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);
}
int PyDict_Merge(PyObject *a, PyObject *b, int override)
Part of the Stable ABI.

Itera sobre el objeto de mapeo b agregando pares clave-valor al diccionario a. b puede ser un diccionario o cualquier objeto que soporte PyMapping_Keys() y PyObject_GetItem(). Si override es verdadero, los pares existentes en a se reemplazarán si se encuentra una clave coincidente en b, de lo contrario, los pares solo se agregarán si no hay una clave coincidente en a. Retorna 0 en caso de éxito o -1 si se lanza una excepción.

int PyDict_Update(PyObject *a, PyObject *b)
Part of the Stable ABI.

Esto es lo mismo que PyDict_Merge(a, b, 1) en C, y es similar a a.update(b) en Python excepto que PyDict_Update() no vuelve a la iteración sobre una secuencia de pares de valores clave si el segundo argumento no tiene el atributo «claves». Retorna 0 en caso de éxito o -1 si se produjo una excepción.

int PyDict_MergeFromSeq2(PyObject *a, PyObject *seq2, int override)
Part of the Stable ABI.

Actualiza o combina en el diccionario a, desde los pares clave-valor en seq2. seq2 debe ser un objeto iterable que produzca objetos iterables de longitud 2, vistos como pares clave-valor. En el caso de claves duplicadas, el último gana si override es verdadero, de lo contrario, el primero gana. Retorna 0 en caso de éxito o -1 si se produjo una excepción. El equivalente en Python (excepto el valor de retorno)

def PyDict_MergeFromSeq2(a, seq2, override):
    for key, value in seq2:
        if override or key not in a:
            a[key] = value