Search code examples
emacslispelisp

Elisp: How to delete an element from an association list with string key


Now this works just fine:

(setq al '((a . "1") (b . "2")))
(assq-delete-all 'a al)

But I'm using strings as keys in my app:

(setq al '(("a" . "foo") ("b" . "bar")))

And this fails to do anything:

(assq-delete-all "a" al)

I think that's because the string object instance is different (?)

So how should I delete an element with a string key from an association list? Or should I give up and use symbols as keys instead, and convert them to strings when needed?


Solution

  • If you know there can only be a single matching entry in your list, you can also use the following form:

    (setq al (delq (assoc <string> al) al)
    

    Notice that the setq (which was missing from your sample code) is very important for `delete' operations on lists, otherwise the operation fails when the deleted element happens to be the first on the list.