1

Q: how can I access a hash table by its value, not its key?

Association lists can be accessed via either their key or their value:

(setq alist '((a .1) (b . 2) (c . 3)))
(assoc 'a alist)                        ; => (a . 1)
(rassoc 3 alist)                        ; => (c . 3)

Is there a hash table analog to rassoc that would allow me to find the key in the hash table associated with value?

0
3
  1. There's no predefined function for this, as far as I know.

  2. It's wrong to speak of the key associated with a given value. There can be more than one key with the same value.

  3. I use these functions (defined in apu.el):

(defun apu-get-hash-keys (value hash-table &optional value-test-function)
  "Return a list of keys associated with VALUE in HASH-TABLE.
Optional arg VALUE-TEST-FUNCTION (default `equal') is the equality
predicate used to compare values."
  (setq value-test-function  (or value-test-function  #'equal))
  (let ((keys  ()))
    (maphash (lambda (key val)
               (when (funcall value-test-function val value)
                 (push key keys)))
             hash-table)
    keys))

(defun apu-get-a-hash-key (value hash-table &optional value-test-function)
  "Return a hash key associated with VALUE in HASH-TABLE.
If there is more than one such key then it is undefined which is
returned.
Optional arg VALUE-TEST-FUNCTION (default `equal') is the equality
predicate used to compare values."
  (setq value-test-function  (or value-test-function  #'equal))
  (catch 'get-a-hash-key
    (maphash (lambda (key val)
               (when (funcall value-test-function val value)
                 (throw 'get-a-hash-key key)))
             hash-table)
    nil))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.