The Computer Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 Iterating Over Keys (Or K/V Pairs) In Zsh Associative Array?
00:34 Accepted Answer Score 52
00:50 Answer 2 Score 41
01:07 Answer 3 Score 2
01:30 Thank you

--

Full question
https://superuser.com/questions/737350/i...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#zsh

#avk47



ACCEPTED ANSWER

Score 52


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.




ANSWER 2

Score 41


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



ANSWER 3

Score 2


In addition to the following accepted answer,

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

if you also want to sort the result by key in ascending order, you can do

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

I usually use latter form as it allows more manipulations in the loop like sorting, filtering, etc.