BaronRandom
BaronRandom

Reputation: 57

how to get index, out of bash array in dictionary

I have this code -->

list=("kek" "lol")
dict+=(["memes"]=$list)

with array, and the dictionary ( i guess ).
now i want to get, for example, second index out of the list, but using dictionary.
Something like echo ${dict[1]}, but that does not print out anything, even tho if to call echo ${dict[0]}, it will print out kek. So my guess that i have done something wrong on declaring dictionary step... and i was not able to google anything about this issue for some reason.
So... How do i do it?

Upvotes: 1

Views: 368

Answers (2)

BaronRandom
BaronRandom

Reputation: 57

Nvm, you can do it with just declaring the dictionary this way dict+=(["memes"]="kek" "lol") , and it will work, still interesting, if it even possible to declare it via variable. Thought i was not able to find a way to get the list out of dictionary using the key (with key-"memes" get the list-value with "kek" and "lol").

So, if someone will be interested how i achived getting the list out of dictionary by the key:

declare -A dict
dict+=( ["memes"]="kek,lol" )
dict+=( ["memes2"]="kek2,lol2" )
for key in ${!dict[@]}
do
    echo "key is: $key"
    IFS=',' read -r -a list_dict <<< "${dict[$key]}"
    for values_by_the_key in ${list_dict[@]}
    do
        echo "value: $values_by_the_key"
    done
done

So, basically it value of the key is not a list, just a string, that is converted then into the list... but it works!:)

Upvotes: 0

user1934428
user1934428

Reputation: 22227

The value of an associative array is always a scalar. It can't be an indexed array. You could store instead the name of the array (list) into the dictionary and use a nameref to access the array:

list=(kek lol)
dict+=([memes]=list) # Store name of array
declare -n plist=${dict[memes]} # Fetch the list
echo ${plist[0]} # Outputs kek

Upvotes: 1

Related Questions