Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Lacking from the simple API of System`Utilities`HashTable is a method to enumerate the keys/values.

?System`Utilities`Hash*

HashTable   HashTableAdd    HashTableContainsQ  HashTableGet    HashTableRemove

After creating a hash table

h = System`Utilities`HashTable[];
System`Utilities`HashTableAdd[h, "a", 1];

Various methods to extract its content fail.

h[[1]]
h
DownValues[h]

Any way out?

share|improve this question
1  
I wonder what HashTableGet[] does... :) –  J. M. Jun 8 '13 at 15:17
    
@0x4A4D I think OP wants to list all available key-value pairs in the table, which I believe is not possible. –  rm -rf Jun 8 '13 at 15:21
2  
If you want to be able to enumerate the contents, you're probably better off just to use ordinary downvalues rather than the System`Utilities`HashTable. –  Oleksandr R. Jun 8 '13 at 19:44
    
Just to follow up on 0x4A4D, you have tried System`Utilities`HashTableGet[h, "a"]? –  Seth Chandler Jun 9 '13 at 5:35

1 Answer 1

up vote 11 down vote accepted

I'm sure there must be a better way, but this works:

h = System`Utilities`HashTable[];
System`Utilities`HashTableAdd[h, "a", 1];
System`Utilities`HashTableAdd[h, "b", 2];

ToExpression[ToString[h, InputForm], InputForm, Hold][[1, 2]]
{{"a", 1}, {"b", 2}}

Mr. Wizard provides a more terse version:

ToHeldExpression[ToString[h, InputForm]][[1, 2]]
share|improve this answer
    
Unless there is something like SparseArray[. . .]["NonzeroPositions"] for HashTable there very well may not be a better way. –  Mr.Wizard Jun 9 '13 at 13:48
    
More terse: ToHeldExpression[ToString[h, InputForm]][[1, 2]] –  Mr.Wizard Jun 9 '13 at 14:55
1  
As with many things Mathematica I learned it from Leonid. It's an old function but still entirely, well, functional. –  Mr.Wizard Jun 10 '13 at 10:13
1  
+1. I still hope there is some more robust way though, since ToString-ToExpression transformation is not always robust. –  Leonid Shifrin Jun 10 '13 at 10:28
1  
@Leonid for testing purposes can you give an example where Simon's method fails? –  Mr.Wizard Jun 10 '13 at 12:01

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.