4
$\begingroup$

suppose I have 2 associations

t1=<|"a" -> 1, "b" -> 2, "c" -> 3, "d" -> 4|> 

and

t2=<|"a" -> x, "a1" -> x^2, "b0" -> x^3, "b" -> x^4, "b1" -> x^5, "c" -> x^6, "c1" -> x^7, "c2" -> x^8, "d" -> x^9|> 

How can I from t2 select those elements that are in t1? The output would look like:

<|"a" -> x, "b" -> x^4,"c" -> x^6, "d" -> x^9|> 

I tried pick as Pick[t2,t1] yet it returns an empty sequence.

$\endgroup$

2 Answers 2

7
$\begingroup$
KeyIntersection[{t1, t2}][[2]] 

<|"a" -> x, "b" -> x^4, "c" -> x^6, "d" -> x^9|>

or

KeyTake[t2, Keys[t1]] 

<|"a" -> x, "b" -> x^4, "c" -> x^6, "d" -> x^9|>

$\endgroup$
8
$\begingroup$
Query[Keys[t1]]@t2 

<|"a" -> x, "b" -> x^4, "c" -> x^6, "d" -> x^9|>

t2[[Keys @ t1]] 

<|"a" -> x, "b" -> x^4, "c" -> x^6, "d" -> x^9|>

KeySelect[t2, AssociationThread[Keys[t1] -> True]] (* or *) KeySelect[t2, MemberQ[Keys[t1], #] &] 

<|"a" -> x, "b" -> x^4, "c" -> x^6, "d" -> x^9|>

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.