Elisp: Association List
Association List (aka alist) is a value type in Emacs Lisp.
Association List is a
, where each element is a cons pair, like this
(cons key value).
(cons a b)
can also be written as
(a . b).
In each cons pair, the key and value can be any value type.
Items in Association List can have duplicate keys, and order is maintained.
If you have more than a thousand items, and need fast random access, better is to use Hash Table .
What's the Difference Between Association List and Hash Table?
- Association List is ordered.
- Association List can have duplicate keys.
- Hash Table keys are unique.
- Hash Table items are not ordered.
- Hash Table is faster for random access when there are huge number of items (over thousands).
Create a AList
(setq x '(("mary" . 23) ("john" . 24) ("smith" . 33)))
Get Pair by Key
(assoc key alist)
Return the first found pair with the key. If key do not exist, return
nil. (key existence is checked by
(setq x '(("mary" . 23) ("john" . 24) ("smith" . 33))) ;; get the pair with key "john" (assoc "john" x) ; returns ("john" . 24)
After you got the cons pair, you can use
car to get the first element, and use
cdr to get the last element.
(setq x '(("mary" . 23) ("john" . 24) ("smith" . 33))) ;; get the value with key "john" (cdr (assoc "john" x)) ; returns 24
Get Pair by Value
You can search alist by value.
(rassq value alist)
Return the first association with value value in alist. It returns
nilif no association in alist has a CDR
(setq x '(("mary" . 23) ("john" . 24) ("smith" . 33))) ;; get the pair with value 24 (rassoc 24 x) ; returns ("john" . 24)
More Alist Functions
Note, Association List is a List , any function that works on list also works on Association List.
[see Elisp: Sequence Functions]
There are many more specialized function for alist. See
(info "(elisp) Association Lists")