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).


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

(sort my-alist '<) ; does not work
  • 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 Sep 3 '17 at 1:09

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.

  • Shouldn't that be (< (cdr a) (cdr b))? – npostavs Aug 3 '17 at 18:49
  • Yes, indeed. Added to the above. Thanks! – Erik Aug 3 '17 at 19:10
  • 1
    PS (cl-sort my-alist #'< :key #'cdr) is another possibility – npostavs Aug 3 '17 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 Sep 2 '17 at 19:52
  • 1
    PPS the Emacs 25+ seq.el library also permits (seq-sort-by #'cdr #'< my-alist), similarly to the cl-sort example above. – Basil Sep 2 '17 at 22:25

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.