If I have an association A with a key of X then Keys[A} yields {...,X...} with X being unevaluated. Now suppose I assign X a value, say 2 for simplicity, then A[X] evaluates as A[2] rather than A[X] and return a failure due to a missing key 2. How do I stop X being evaluated so I can treat it as a symbolic value?

  • 1
    $\begingroup$ This sounds like a recipe for making an unusable Association, and bad practice. Is there a reason to do things this way? Why not use strings for keys instead of symbols? $\endgroup$ – Jason B. Dec 4 '19 at 15:17
  • $\begingroup$ Mea culpa! I’m too used to LISP $\endgroup$ – Nick Dec 4 '19 at 15:19

You can do this by either using Unevaluated or by Blocking the key:

Clear[assoc, x];
assoc = <|x -> 1|>
x = 2;
Block[{x}, Lookup[assoc, x]]

<|x -> 1|>

<|x -> 1|>

Missing["KeyAbsent", 2]



To obtain the keys without evaluating them, use the newly added (in V12, IIRC) 2nd argument of Keys:

Keys[assoc, Hold]



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.