pythonarrayspython-3.xassociative

Access data in python3 associative arrays


I'd like how to create and print associative arrays in python3... like in bash I do:

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

In bash I can do echo "${array["beta",1]}" to access data to print "text2".

How can I define a similar array in python3 and how to access to data in a similar way? I tried some approaches, but none worked.

Stuff like this:

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

But I can't access to data with print(array['beta', 1]). It is not printing "text2" :(


Solution

  • It looks like you want a dictionary with compound keys:

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