Delete item from PyDict by exact value and hash

Beware that the implementation of the routine here relies on implementation details of CPython’s dict that go beyond the published API. This file depends on python version when cythonized. It expects PY_VERSION_HEX to be available in the cythonization and the result depends on it (and needs to match the python version the C-compiler compiles it against). Usage should do something along the lines of

cythonize(“dict_del_by_value.pyx”,
compile_time_env({“PY_VERSION_HEX”: sys.hexversion}))

AUTHORS:

  • Nils Bruin (2017-05)
sage.cpython.dict_del_by_value.test_del_dictitem_by_exact_value(D, value, h)

This function helps testing some cdef function used to delete dictionary items.

INPUT:

  • D – a Python <dict>.
  • value – an object that is value D.
  • h – the hash of the key under which to find value in D.

The underlying cdef function deletes an item from D that is in the hash bucket determined by h and whose value is identic with value. Of course, this only makes sense if the pairs (h, value) corresponding to items in D are pair-wise distinct.

If a matching item can not be found, the function does nothing and silently returns.

See trac ticket #13394 for a discussion.

sage: from sage.cpython.dict_del_by_value import test_del_dictitem_by_exact_value
sage: B=1000
sage: L=list(range(B))
sage: D1=dict()
sage: D2=dict()
sage: for i in range(100000):        # long time
....:     ki=L[floor(random()*B)]
....:     vi=L[floor(random()*B)]
....:     D1[ki]=vi
....:     D2[ki]=vi
....:     ko=L[floor(random()*B)]
....:     if ko in D1:
....:         vo=D1[ko]
....:         del D1[ko]
....:         test_del_dictitem_by_exact_value(D2,vo,hash(ko))
....:     assert D1 == D2

No action is taken if the item prescribed by key hash and value does not exist in the dictionary:

sage: D = {1: ZZ}
sage: test_del_dictitem_by_exact_value(D, ZZ, 2)
sage: D
{1: Integer Ring}
sage: test_del_dictitem_by_exact_value(D, QQ, 1)
sage: D
{1: Integer Ring}