Elisp: Sort Hash Table 🚀

By Xah Lee. Date: . Last updated: .

Sort Hash

To sort, first change it to a list.

;; make hash table
(setq xx (make-hash-table :test 'equal))
(puthash "joe" 19 xx)
(puthash "jane" 20 xx)
(puthash "carrie" 17 xx)
(puthash "liz" 21 xx)

;; convert hash table to list
(setq xlist
      (let ((yy nil))
        (maphash
         (lambda (k v)
           (push (list k v) yy))
         xx)
        yy))

;; sort by key
(setq xlist (sort xlist (lambda (a b) (string< (car a) (car b)))))

(print xlist)
;; (("carrie" 17) ("jane" 20) ("joe" 19) ("liz" 21))

;; sort by value
(setq xlist (sort xlist (lambda (a b) (< (nth 1 a) (nth 1 b)))))

(print xlist)
;; (("carrie" 17) ("joe" 19) ("jane" 20) ("liz" 21))

🛑 WARNING: elisp's sort function is destructive. Once sort is used on a variable, that variable's value is essentially destroyed. (the sorted result is returned.) If you want to keep the variable, make a copy first.

Rearrangement (ELISP Manual)

Elisp, Hash Table