I've found a simple approach using the function Part
(its shorthand is [[ ]]
):
1.
If you write your list lst1
rather that way:
newlst1 = {{"A", "a"}, {"D", "dd"}, {"B"}}
you can assign any value (for example here 999
) to all these keys simply with:
(assc[[##]] = 999) & @@@ newlst1;
You can check the result:
assc
<|"A" -> <|"a" -> 999, "aa" -> 2|>, "B" -> 999, "C" -> 5,
"D" -> <|"d" -> 2, "dd" -> 999|>|>
2.
Allright, let's say you don't want to modify your lst1={"a", "dd", "B"};
,
the keys are unique so you don't want to loose your time.
Then, we'll just need to generate this key map first in order to help us:
keymap = Reap@MapIndexed[Sow[Rest@{##}] &, assc, {0, Infinity}] //
Flatten[#, 3] & // DeleteCases[#, {}] & // Map[#[[-1, 1]] -> # &, #] &
{"a" -> {Key["A"], Key["a"]}, "aa" -> {Key["A"], Key["aa"]},
"A" -> {Key["A"]}, "B" -> {Key["B"]}, "C" -> {Key["C"]},
"d" -> {Key["D"], Key["d"]}, "dd" -> {Key["D"], Key["dd"]},
"D" -> {Key["D"]}}
Then for example to assign a value, you just do (almost as in 1./):
(assc[[##]] = 111111) & @@@ (lst1 /. keymap);
You can check:
assc
<|"A" -> <|"a" -> 111111, "aa" -> 2|>, "B" -> 111111, "C" -> 5,
"D" -> <|"d" -> 2, "dd" -> 111111|>|>
Explanation
You can use Part
or [[ ]]
with Associations almost as you do with List
s, except you use Keys as parameters (see the Part doc.).
Let's try some examples:
Given
assc = <|"A" -> <|"a" -> 1, "aa" -> 2|>, "B" -> 0, "C" -> 5,
"D" -> <|"d" -> 2, "dd" -> 12|>|>
see what does:
assc[["A"]]
<|"a" -> 1, "aa" -> 2|>
assc[["A", "a"]]
1
and you can directly assign new values:
assc[["A", "a"]] = 123456789;
assc
<|"A" -> <|"a" -> 123456789, "aa" -> 2|>, "B" -> 0, "C" -> 5, "D" ->
<|"d" -> 2, "dd" -> 12|>|>