In python, I can do this in one line:
>>> for key, value in dict(j=1, k=2).items():
... print(key, value)
...
j 1
k 2
>>>
In bash, I can do this:
$ map=([j]=1 [k]=2); for key in ${!map[@]}; do value=${map[$key]}; echo $key $value; done
j 1
k 2
$
Is there a way in bash to "inline" map declaration into for – similarly how it’s possible in the python example – instead of declaring it beforehand?
The reason I’m looking for this is to avoid having to declare two additional variables map and value separately – in other words, to make this shorter if possible when doing one-liners on the command line.
>Solution :
There’s no way around doing
declare -A map=([j]=1 [k]=2)
The "${!map[@]}" parameter expansion requires a declared parameter.
Actually, not true. The parameter expansion happily expands an unset variable into the empty string.
You can drop the value variable
for key in "${!map[@]}"; do
printf '%s %s\n' "$key" "${map[$key]}"
done
Note that associative arrays are unordered. My output for that loop is
k 2
j 1
If you are just looking for a quick way to inspect the contents of a variable, use declare -p
declare -A map=([j]=1 [k]=2)
declare -p map
outputs
declare -A map=([k]="2" [j]="1" )