1

I'd like to create a hash table with data already in it. I know I can do so as follows:

(let ((my-table (make-hash-table)))
  (puthash 'k1 'v1 my-table)
  (puthash 'k2 'v2 my-table)
  (puthash 'k3 'v3 my-table)
  my-table)

But there's a lot of boilerplate here. Compare to creating the same table in, for example, Clojure:

{'k1 'v1 'k2 'v2 'k3 'v3}

Is there a more concise way to create a hash table with data in it?

zck
  • 8,984
  • 2
  • 31
  • 65
  • 1
    The [ht library](https://github.com/Wilfred/ht.el) contains a bunch of convenience functions for hashtables, including a function to construct them like this: `(ht (k1 v1) (k2 v2) (k3 v3))`. – Omar Oct 19 '15 at 21:14

1 Answers1

4

You can use the printed representation for a hash table. From the Emacs documentation:

You can also create a new hash table using the printed representation for hash tables. The Lisp reader can read this printed representation, provided each element in the specified hash table has a valid read syntax (see Printed Representation). For instance, the following specifies a new hash table containing the keys key1 and key2 (both symbols) associated with val1 (a symbol) and 300 (a number) respectively.

#s(hash-table size 30 data (key1 val1 key2 300))

It goes on with a warning for certain data types:

Note that you cannot specify a hash table whose initial contents include objects that have no read syntax, such as buffers and frames. Such objects may be added to the hash table after it is created.

So we can create the same hash table as the question in this way:

#s(hash-table data (k1 v1 k2 v2 k3 v3))

Any attributes not provided (that is, size, test, rehash-size, and rehash-threshold) are set to their default values.

zck
  • 8,984
  • 2
  • 31
  • 65