Search code examples
emacselisp

Elisp - Loop over an alist


What's the best way to loop over an alist and do something with each pair in Emacs Lisp? I suppose a macro wouldn't be difficult, I'm just wondering if this is built in somewhere. Is there a more elegant way than below?

(setq my-list '((a . 1)
                (b . 2)
                (c . 3)))

(loop for key in (mapcar 'car my-list)
      for value in (mapcar 'cdr my-list)
      collect (cons value key))

;; Returns this
((1 . a)
 (2 . b)
 (3 . c))

Solution

  • cl-loop from cl-macs.el has support for destructing like CL:

    (cl-loop for (key . value) in my-list
          collect (cons value key))