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?

1
  • 1
    The ht library 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, 2015 at 21:14

1 Answer 1

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.

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.