# Extracting values from association via Cases

I have an association of the form

temp = <|"u" -> -5, "v" -> -5|> -> -30

and want to extract the numerical values, after a bit of trying I found

Cases[temp, _Integer, \[Infinity]]

does the job. My first attempt was to rebuild the structure, like:

Cases[temp, <|u -> x_, v -> y_|> -> z_ :> {x, y, z}]

which does not work, due to the variables "u", "v", I assume. But also this does not work:

Cases[temp, <|_ -> x_, _ -> y_|> -> z_ :> {x, y, z}]

and I wonder why, the pattern should match. Can someone explain?

• Values@Keys@temp~Join~{Values@temp}
– Syed
Commented Sep 15, 2022 at 6:21
• ReplaceAll[temp, HoldPattern[KeyValuePattern[{_ -> x_, _ -> y_}] -> z_] :> {x, y, z}]. Commented Sep 15, 2022 at 6:22
• @Syed Close to my first attempt: {Values@Keys[temp], Values[temp]} // Flatten ;-) Commented Sep 16, 2022 at 5:22

According the the Docs for Cases,

The default value for levelspec in Cases is {1}.

You operate on the level {0}, so specify this level explicitly:

Cases[temp, HoldPattern[<|_ -> x_, _ -> y_|> -> z_] :> {x, y, z}, {0}]

{{-5, -5, -30}}


You can also use KeyValuePattern:

Cases[temp, HoldPattern[KeyValuePattern[{_ -> x_, _ -> y_}] -> z_] :> {x, y, z}, {0}]

{{-5, -5, -30}}


Alternatively, use Replace or ReplaceAll:

ReplaceAll[temp, HoldPattern[<|_ -> x_, _ -> y_|> -> z_] :> {x, y, z}]

{-5, -5, -30}

• Thanks for this fast answer! I didn't had in mind HoldPattern.... Commented Sep 15, 2022 at 7:03

Let's say temp had a string value in there as well:

temp = <|"u" -> -5, "v" -> -5, "w" -> "a"|> -> -30


In order to select integers only:

Cases[temp, _Integer, {2}]~Join~Cases[temp, _Integer]


{-5, -5, -30}