# Ordered associations

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

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

• Associations are ordered. – Leonid Shifrin Mar 27 '15 at 2:26
• @Leonid Shifrin, any reference? I could not find. – denfromufa Mar 27 '15 at 2:28
• 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. – Leonid Shifrin Mar 27 '15 at 11:15
• 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. – Niki Estner Apr 5 '15 at 11:25

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.

• 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. – alancalvitti Mar 27 '15 at 3:49
• @m_goldberg, is this guaranteed behavior? You did not show operations such as deletion of key-value pairs – denfromufa Mar 27 '15 at 20:31
• @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. – m_goldberg Mar 27 '15 at 21:43