Sometimes, we only need to store the keys which will be checked whether certain keys exist in the data structure(corresponding data structures in C++ are std::set or std::unordered_set). Despite the presence of the old posts such as Implementing a dictionary data structure and https://stackoverflow.com/questions/1392007/is-there-hashtable-structure-in-wolfram-mathematica, now that we have Association since 10.0, I guess there must be a natural way using Association to achieve this goal.

Of course, one straightforward way might be to introduce an arbitrary expression as a value corresponding each key. However, I am searching for the most memory (or time) efficient way to do it. (i.e., I want to find a way to minimize the overhead due to this unnecessary value)

x = <| a -> "Garbage", b -> "Gabage"|>;

Out[1]= Garbage
Out[2]= Missing["KeyAbsent", c]

There is no native MMA object to handle hashed sets yet. Meanwhile I use this approach:

x = <| a -> True, b -> True|>;

Now, for looking for elements we can do:

Lookup[x, a, False]
Lookup[x, c, False]



And for a lookup list:


{True, True, False}


The approach of @Murta is the one I'm now using too.

I just want to add, for performance and memory concerns, that, when feasible, sometimes, it is more efficient to store the elements not in the set, so practically reversing that approach.

More explicitely, if you know that the majority of the elements of a space $X$ are likely to belong to a subset $A \subset X$, it is more convenient to store in an Association the elements of $X-A$, i.e. Complement[X, A]

C = <| a -> False, b -> False|>;

Then you reverse the lookup:

Lookup[C, a, True]
Lookup[C, c, True]

and you still get if the elements belongs to $A$ but more faster and with less memory consumed.


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.