Elisp: Association List

By Xah Lee. Date: . Last updated: .

Associative List (aka “alist”) is a datatype in Emacs Lisp.

Alist is a list, where each element is a cons pair, like this (cons key value).

Note: (cons a b) can also be written as (a . b).

In each cons pair, the key and value can be any datatype.

Alist is used similar to Python Dictionary , or Ruby Hash Table table, or Java's Map datatype.

Items in alist can have duplicate keys, and order is maintained.

Note: elisp also has true hash table.

〔►see Elisp: Hash Table

What's the Difference Between Alist and Hash Table?

Create a Alist

Because alist is a list, any function that works on list also works on alist.

〔►see Elisp: List

;; set x to a alist
(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

Alist Functions

There are functions that's designed for working with alist. For example, get the pair of a given key. or get the pair of a given value.

Here's the most useful functions for working with alist.

Get Pair by Key

Use assoc to get the pair of a given key. It returns the first found pair with the key. If the alist does not have the key, returns nil. (the key existence is checked by using equal.)

Syntax:

(assoc key alist)

;; set x to a alist
(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.

;; set x to a alist
(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.

Use rassq

Syntax:

(rassq value alist)

returns the first association with value value in alist. It returns nil if no association in alist has a CDR eq to value.

;; set x to a alist
(setq x
      '(("mary" . 23)
        ("john" . 24)
        ("smith" . 33)))

;; get the pair with value 24
(rassoc 24 x)
; returns ("john" . 24)

More Alist Functions

(info "(elisp) Association Lists")

Data Structure Topic

  1. Elisp: Sequence: List, Array
  2. Elisp: Vector
  3. Elisp: List
  4. Elisp: Association List
  5. Elisp: Property List
  6. Elisp: Symbol Property List
  7. Elisp: Map / Loop Thru List / Vector
  8. Elisp: Filter a List
  9. Elisp: Hash Table
Liket it? Put $5 at patreon. Or Buy Xah Emacs Tutorial. Thanks.