6
$\begingroup$

Here is the association I have:

assc = {"abc" -> 2.456, "efg" -> 3.652, "_final" -> 6.108}

I need to remove all key-value pairs where keys start with '_'. I am new to Mathematica, so can anyone please help me out with this. I have a condition (mentioned below), I just don't know how to apply it on an association using 'select'?

The condition I have is:

(StringStartsQ[Keys[assc], "_"])

Output:= {False, False, False, False, False, False, False, False, False, \
False, False, False, False, False, True, True, True, True, True}
$\endgroup$
2
  • 1
    $\begingroup$ Try Pick[assc, StringStartsQ[Keys[assc], Except["_"]]] $\endgroup$
    – Coolwater
    Jun 15, 2018 at 19:30
  • 1
    $\begingroup$ Point of information: assc = {"abc" -> 2.456, ... } is a list of rules not an association. $\endgroup$
    – Edmund
    Jun 15, 2018 at 20:20

1 Answer 1

3
$\begingroup$

Select

Select[
 assc
 , Not[
   StringStartsQ[
    Keys[#]
    , "_"
    ]
   ] &
 ]

DeleteCases

DeleteCases[
 assc
 , _?(StringStartsQ[Keys[#], "_"] &)
 ]

KeySelect

Thanks to @JasonB for this solution.

KeySelect[
 assc
 , Not@*StringStartsQ["_"]
 ]
$\endgroup$
7
  • 1
    $\begingroup$ You can shorten it a bit with KeySelect[ assc, Not@*StringStartsQ["_"]] $\endgroup$
    – Jason B.
    Jun 15, 2018 at 19:26
  • $\begingroup$ @JasonB. Thanks! Didn't know about that one! Incorporated to the answer. $\endgroup$
    – rhermans
    Jun 15, 2018 at 19:29
  • $\begingroup$ @rhermans: Thank you so much for your help. Unfortunately the solutions using 'Select' and 'DeleteCases' did not produce the correct result, I'm still trying on making it work. $\endgroup$ Jun 15, 2018 at 22:17
  • $\begingroup$ @JasonB. Thank you! The solution worked. Much appreciated! :) $\endgroup$ Jun 15, 2018 at 22:18
  • $\begingroup$ @Rajat Bhattacharjee Your edit was somewhat too extensive. That's why I voted for its rejection. However, I see that you found several caveats and their resolutions. Hence, I would like to encourage you to post your edit it as a separate answer. $\endgroup$ Jun 15, 2018 at 22:42

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.