python - 访问 python3 关联数组中的数据

标签 python arrays python-3.x associative

我想知道如何在 python3 中创建和打印关联数组...就像在 bash 中一样:

declare -A array
array["alfa",1]="text1"
array["beta",1]="text2"
array["alfa",2]="text3"
array["beta",2]="text4"

在 bash 中,我可以执行 echo "${array["beta",1]}" 来访问数据以打印“text2”。

如何在 python3 中定义类似的数组以及如何以类似的方式访问数据?我尝试了一些方法,但都没有奏效。

像这样的东西:

array = ()
array[1].append({
            'alfa': "text1",
            'beta': "text2",
        })

但我无法使用 print(array['beta', 1]) 访问数据。它不打印“text2”:(

最佳答案

看起来你想要一个带有复合键的字典:

adict = {
    ("alfa", 1): "text1",
    ("beta", 1): "text2",
    ("alfa", 2): "text3",
    ("beta", 2): "text4"
}

print(adict[("beta", 1)])

关于python - 访问 python3 关联数组中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73392878/

相关文章:

arrays - 在matlab中对结构体中的数据进行向量化

python - python 列表理解中的 if-else

python-3.x - 这个函数声明中 -> List[int] 是什么意思?

python - TypeError : str, 字节或字节数组预期,而不是列表

python - mysql.connector.errors.ProgrammingError : 1064 (4200): You have an error in your SQL syntax;

javascript - JavaScript Code School "Closures"任务中的打印问题

python - 使用 cppyy 从 Python 解析 C (C++) 调用方法

javascript - 循环对象数组 - TypeError : Cannot read property 'name' of undefined

python - 在数据框中用 nan 替换特定值

python - scikit-learn 中的样本权重在交叉验证中被破坏