pucktack
pucktack

Reputation: 93

2D list python unable to get it right

im trying to the below code but when I run the function for examnple:

finder("001-987654-003")

Nothing is happening. What went wrong?

def finder(lookupvalue):
    user_list = [
        ["Account number","Currency","Balance"],
        ["001-987654-003","USD",1300.72],
        ["001-919202-100","EUR",105.01],
        ["001-905700-100","EUR",305.00],
        ["001-908415-307","CHF",20804.98],
        ["011-974777-200","PLN",208.15],
        ["001-931654-001","USD",450.7]
    ]
    
    for row in user_list:
        if user_list[0][0]==lookupvalue:
            print("yes")

Upvotes: 0

Views: 98

Answers (3)

realFishSam
realFishSam

Reputation: 189

Try using a dictionary:

user_list = {
    "Account Number": ["001-987654-003", "001-919202-100", "001-905700-100"],
    "Currency": ["USD", "EUR", "EUR"],
    "Balance": [1300.72, 105.01, 305.00]
}

Seems more appropriate in your case as you're trying to store different lists (I think).

Upvotes: 1

I'mahdi
I'mahdi

Reputation: 24059

try this:

user_list = [
        ["Account number", "Currency", "Balance"],
        ["001-987654-003", "USD", 1300.72],
        ["001-919202-100", "EUR", 105.01],
        ["001-905700-100", "EUR", 305.00],
        ["001-908415-307", "CHF", 20804.98],
        ["011-974777-200", "PLN", 208.15],
        ["001-931654-001", "USD", 450.7]
    ]

def finder(lookupvalue, lookuplist, col_index):
    for row in user_list:
        if row[0] == lookupvalue:
            print(row[col_index-1])
            
            
finder("001-919202-100", user_list, 2)

output:

EUR

Upvotes: 2

U13-Forward
U13-Forward

Reputation: 71610

You have to use row instead of user_list:

def finder(lookupvalue, lookuplist, col_index):
    for row in lookuplist:
        if row[0] == lookupvalue:
            print(row[col_index - 1])

finder("001-919202-100", user_list, 2)

That's because if you use user_list[0][0] in the for loop it'll constantly refer to "Account number" whilst row[0] will go through the different lists, looking up the account number.

But as one of the comments said, a dictionary would probably be better for this task.

Upvotes: 3

Related Questions