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

In zsh, I want to iterate over an associative array. I need both keys and values. But when I iterate over the associative array normally (for x in $assoc_array), I get only values.

All examples I've looked at show that, given a key, you can get its value from an associative array. My problem is getting the set of keys to begin with.

Does zsh support iterating over keys in an associative array?


Solution 1:

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.

Solution 2:

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