Home > front end >  Access data in python3 associative arrays
Access data in python3 associative arrays

Time:08-18

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" :(

CodePudding user response:

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)])

CodePudding user response:

This code is wrong, it gives an error:

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

One way to achieve what you are looking for is with this code, using a list:

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

Printed output:

text2

CodePudding user response:

Try

arry = []

arry.append({"alpha":"text1",
                 "beta": "text2"})
arry.append({"alpha":"text3",
                 "beta": "text4"})

for i,_ in enumerate(arry):
    print(arry[i]["alpha"])
    print(arry[i]["beta"])

#or

for i,element in enumerate(arry):
    print(element["alpha"])
    print(element["beta"])
  • Related