Iterating over two nested levels and then compiling a map from the results is a very common pattern in Terraform - it’s a bit complex how it needs to be written, though.
I’m on mobile right now so can’t type complex code, but here’s the last time I answered approximately this question: Attach multiple policy to single SSO permission set - #2 by maxb
You should be able to adapt the code I have there to do what you want, by swapping out some of the subexpressions.
Any problems, comment here and I’ll be more explicit when I have a real keyboard to work with.