Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simplify Python array retrieval of values

I have the following code at the moment which works perfectly:-

my_array = [
    ['var1', 1], ['var2', 2], ['var3', 3], ['var4', 4], ['var5', 5]
]

for i in range(len(my_array)):
    if my_array[i][0] == "var1":
        var_a = my_array[i][1]
    elif my_array[i][0] == "var2":
        var_b = my_array[i][1]
    elif my_array[i][0] == "var3":
        var_c = my_array[i][1]
    elif my_array[i][0] == "var4":
        var_d = my_array[i][1]
    elif my_array[i][0] == "var5":
        var_e = my_array[i][1]
        
print(var_a)
print(var_b)
print(var_c)
print(var_d)
print(var_e)

Is there a way I can simplify the way I get the values, instead of using multiple "elif’s"?

I tried something like this:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var_f = my_array[i]["var1"]
print(var_f)

but I get an error:-

TypeError: list indices must be integer, not str

Any help would be very much appreciated!

Thank you

>Solution :

You can convert my_array to dict to simplify the retrieval of values:

my_array = [["var1", 1], ["var2", 2], ["var3", 3], ["var4", 4], ["var5", 5]]

dct = dict(my_array)

# print var1
print(dct["var1"])

Prints:

1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading