5
$\begingroup$

Mathematica 10 has introduced Associations, elsewhere known as hash tables or dictionaries. Is there Ordered equivalent like in Python, Java, .NET? The data structure should remember the order in which key-value is inserted.

https://docs.python.org/2/library/collections.html

http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

https://msdn.microsoft.com/en-us/library/system.collections.specialized.ordereddictionary(v=vs.110).aspx

$\endgroup$
  • 4
    $\begingroup$ Associations are ordered. $\endgroup$ – Leonid Shifrin Mar 27 '15 at 2:26
  • $\begingroup$ @Leonid Shifrin, any reference? I could not find. $\endgroup$ – denfromufa Mar 27 '15 at 2:28
  • 2
    $\begingroup$ Apparently, this seems to not be mentioned in the docs explicitly, at least not on the main Association doc page. One can sort of figure this out by the fact that one can use Part with numerical indices on associations, but such fundamental property should be mentioned explicitly. I will file a suggestion report. $\endgroup$ – Leonid Shifrin Mar 27 '15 at 11:15
  • $\begingroup$ Not exactly a reference, but Sort and KeySort return sorted associations (and that's documented behavior). That wouldn't make any sense if associations were unordered. $\endgroup$ – Niki Estner Apr 5 '15 at 11:25
8
$\begingroup$

That associations are ordered can be easily demonstrated.

assoc = <|a -> x, b -> y, c -> z|>;

assoc[d] = 42; assoc
<|a -> x, b -> y, c -> z, d -> 42|>
assoc[a] = w; assoc
<|a -> w, b -> y, c -> z, d -> 42|>

Since the key d did not exist, the key, value pair d -> 42 was added to the end of the association. On the hand since the key a did exist, it's position was preserved.

$\endgroup$
  • 1
    $\begingroup$ assoc = <|b -> x, c -> y, d -> z|>; assoc[a] = 42; assoc (* <|b -> x, c -> y, d -> z, a -> 42|> *), so order in Association means insertion order, as opposed to the infinite universe of orders (reflexive, antisymmetric relation) that one might imagine, eg lex order. $\endgroup$ – alancalvitti Mar 27 '15 at 3:49
  • $\begingroup$ @m_goldberg, is this guaranteed behavior? You did not show operations such as deletion of key-value pairs $\endgroup$ – denfromufa Mar 27 '15 at 20:31
  • $\begingroup$ @denfromufa. I can't guarantee any behavior, but all the ways I know of that can delete a pair preserve the order. Obviously some operations, such as Sort, KeySort, etc., don't preserve order because their purpose is to change it. I would recommend that you just try any operation you are suspicious of and see what happens. Mathematica is so interactive that is trivial to make such experiments. $\endgroup$ – m_goldberg Mar 27 '15 at 21:43

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.