Sign in

How to use shell to realize the function similar to that in Python dict.get The function of ()

wpqwi edited in Fri, 23 Sep 2022

I don't have much contact with the shell. I want to ask if there is a get function similar to a python dictionary in the shell, that is, the corresponding way of key and value. In fact, we need to use this way, mainly in Python dict.get There is a way to return the default value if K is not found, for example: v = d.get ('k ','default'). If K is found, the corresponding value will be returned, and if K is not found, the corresponding 'default' will be returned. Actually, I want to ask if there are similar functions in the shell. Because I have only studied python, I can only make an analogy like this.

2 Replies
commented on Fri, 23 Sep 2022

Yujiaao has talked about the usage of associative arrays in bash. Bash's associative array can't preset the default value. The value that can't be obtained by pressing key is empty character. You can write such a code block yourself

dict_get() {
    if [[ $val == "" ]]
        echo $default
        echo $val

# 测试
declare -A arr
arr+=( ["key2"]=val2 ["key3"]=val3 )

v1=$(dict_get arr key1 0)
v2=$(dict_get arr key4 0)
echo $v1
echo $v2
commented on Fri, 23 Sep 2022

Associative array is introduced in Bash 4.

declare -A arr


arr+=( ["key2"]=val2 ["key3"]=val3 )
#arr数组现在包含三个键值对。Bash 关联数组功能是相当有限的,没有排序或弹出等。

for key in ${!arr[@]}; do
    echo ${key} ${arr[${key}]}

All key values are traversed and echoed.

MacOS only contains bash3 because of authorization problems . 2, if you want to use 4 . The version above 0 needs to be downloaded and installed by yourself. Use bash to view the version -- version .