Home > Net >  Simplify Python array retrieval of values
Simplify Python array retrieval of values

Time:12-03

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

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

CodePudding user response:

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
  • Related