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?

Best Answer

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"

See Parameter Expansion Flags in the Zsh manual.