2
$\begingroup$

Considering we have an Association:

<|a -> tr, b -> <|c -> <|d -> 12, e -> del, f -> <|h -> true, i -> false|>|>|>|>

How can I iterate through it, and delete the key->val where val === del and update the values that are true or false to be True and False,so that having as a result:

  <|a -> tr, b -> <|c -> <|d -> 12, f -> <|h -> True, i -> False|>|>|>|>

Thanks!

$\endgroup$
3
$\begingroup$

You can use a combination of DeleteCases and ReplaceAll to accomplish this for your particular example:

data =  <|a -> tr, b -> <|c -> <|d -> 12, e -> del, f -> <|h -> true, i -> false|>|>|>|>;
DeleteCases[
  ReplaceAll[data, {true -> True, false -> False}],
  del,
  Infinity]

<|a -> tr, b -> <|c -> <|d -> 12, f -> <|h -> True, i -> False|>|>|>|>

The Infinity, the last argument of DeleteCases, specifies that the deletion should occur at every level (and not just on the outer association). When you use DeleteCases on an association, it matches on the values of the association, so simply matching on del is sufficient in this case.

Note that if you explicitly want to check for a value being the same (=== or SameQ) as del, then you would want to replace the argument del to DeleteCases above with something like val_ /; val === del.

$\endgroup$
  • $\begingroup$ And what if I would also like to check the Keys? e.g. if the key is e I don't want to do anything with that pair? $\endgroup$ – SuTron May 11 '15 at 9:15
  • $\begingroup$ In that case, you'd probably want something like Association@DeleteCases[Normal[a], (Except[e] -> del)]; the Normal call just turns the association into a list of rules so you can match on the entire rule; the (Except[e] -> del) is just a pattern that matches anything but e as the lhs of the rule and del as the rhs. $\endgroup$ – nben May 11 '15 at 15:41

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.