6

Is there a way to sort an association list? In my case I would like to sort the alist elements by the values in each list element (represented by the integers in the example below).

Example:

(setq my-alist '((red . 2) (blue . 1) (yellow . 8) )) ; make an alist

(sort my-alist '<) ; does not work
1
  • Make sure you know what you're doing. The element returned by assq and friends is the first matching element, and therefore changing the order of the list can (potentially, depending on the alist) change the value obtained.
    – phils
    Commented Sep 3, 2017 at 1:09

1 Answer 1

7

At the excellent ergo emacs on hash tables (http://ergoemacs.org/emacs/elisp_hash_table.html) I found out this also works for alists:

(sort my-alist (lambda (a b) (string< (car a) (car b))))

...which sorts by the colors in the example, and consequently:

(sort my-alist (lambda (a b) (< (cdr a) (cdr b))))

...which sorts by the numbers in the example.

5
  • Shouldn't that be (< (cdr a) (cdr b))?
    – npostavs
    Commented Aug 3, 2017 at 18:49
  • Yes, indeed. Added to the above. Thanks!
    – Erik
    Commented Aug 3, 2017 at 19:10
  • 1
    PS (cl-sort my-alist #'< :key #'cdr) is another possibility
    – npostavs
    Commented Aug 3, 2017 at 19:53
  • Since this post answers your question, could you please accept your own answer so we can mark the question as done?
    – Dan
    Commented Sep 2, 2017 at 19:52
  • 4
    PPS the Emacs 25+ seq.el library also permits (seq-sort-by #'cdr #'< my-alist), similarly to the cl-sort example above.
    – Basil
    Commented Sep 2, 2017 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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