Is there way to slice an Association with named key span?
Span currently doesn't accept named keys:
<|"z" -> 1, "x" -> 2, "b" -> 3, "a" -> 4|> // Query["x" ;; "a"]
Missing["PartInvalid", "x" ;; "a"]
And neither does passing Key["x"] and Key["a"] to Span.
Here is a workaround using Position - which only matches Values in an Association - so relies on 1. normalizing, 2. projecting the first component of the matching Positions then 3. querying the rebuilt association using the resulting position Span.
keySpan[k1_, k2_][as_Association] :=
Query[{Identity, Normal /* Position[k1 | k2] /* Map[First] } /*
Replace[{a_, pos_} :> Query[Span[pos]][a]]][as];
Then:
<|"z" -> 1, "x" -> 2, "b" -> 3, "a" -> 4, "c" -> 5|> // keySpan["x", "a"]
<|"x" -> 2, "b" -> 3, "a" -> 4|>
Is there a method that avoids normalizing the association?