Search code examples
emacselisp

How to retrieve value of cons cell by key name?


Say I have a list of cons cells like so:

(setq foo '(("a" . 1) ("b" . 2) ("c" . 3)))

And I'd like to retrieve the value of a particular cons cell by "key name". Is there a function that will let me do this?

E.g.

(get-by-key "a" foo) ;; => 1

Or something similar. Thanks in advance!


Solution

  • Such list is called an association list, or alist for short. Formally, an association list is a list of conses of a key and its associated value.

    The assoc function is what you are looking for. It takes a key and an alist as its arguments and returns the first association for the key in the alist in terms of equal:

    ELISP> (setq foo '(("a" . 1) ("b" . 2) ("c" . 3)))
    (("a" . 1)
     ("b" . 2)
     ("c" . 3))
    
    ELISP> (assoc "a" foo)
    ("a" . 1)
    
    ELISP> (cdr (assoc "a" foo))
    1
    

    The assoc-string function is similar to the assoc function but specific to association lists whose keys are strings. In addition to a key and an alist, it can take another optional argument that makes the key comparison case-insensitive:

    ELISP> (assoc-string "a" foo)
    ("a" . 1)
    
    ELISP> (assoc-string "A" foo)
    nil
    
    ELISP> (assoc-string "A" foo t)
    ("a" . 1)
    

    For the full list of association list-related functions, refer to GNU Emacs Lisp Reference Manual.