3
$\begingroup$

related: Extracting values from Associations

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?

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

2 Answers 2

4
$\begingroup$

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}
$\endgroup$
1
  • $\begingroup$ Thanks for this fast answer! I didn't had in mind HoldPattern.... $\endgroup$
    – mgamer
    Sep 15 at 7:03
2
$\begingroup$

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}

$\endgroup$

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.