Iterating over keys (or k/v pairs) in zsh associative array?

I continued searching after asking my question and found this answer on the Unix StackExchange:

typeset -A assoc_array
assoc_array=(k1 v1 k2 v2 k3 v3)

for k in "${(@k)assoc_array}"; do
  echo "$k -> $assoc_array[$k]"
done

Output is:

k1 -> v1
k2 -> v2
k3 -> v3

You can get both keys and values at once with this nifty parameter expansion:

for key val in "${(@kv)assoc_array}"; do
    echo "$key -> $val"
done

See Parameter Expansion Flags in the Zsh manual.

Tags:

Zsh