Home > Software design >  Python fetching element from 2d list and changing based on user input
Python fetching element from 2d list and changing based on user input

Time:12-06

I am super new to programming so sorry if this is a common question. I am trying to alter elements such as first name/last name etc in a 2d list whereby a user inputs a username, if the username returns true then the user is asked to select an option of what they would like to change first name or last name. My code only changes the first name or last name of the first list within the 2d list. Does anyone know how to specifically target a list element based on a users selection of an element within that list? any help would be greatly appreciated :).

allUserDetails = [["John", "Doe", "User", "Sales", "johndoe91", "password"],
                  ["James", "Hill", "Admin", "Administrator", "hill95", "12345678"]]


def update_user():
    print("\n:: Update User ::")
    print("-" * 25)
    print("\nWhich field would you like to update?\n")
    print("1. First Name")
    print("2. Last Name")


print(allUserDetails)
searchUser = input("\nInput username to edit (press 1 to return to Main Menu): ").lower()

while searchUser != "1":
    for x in allUserDetails:
        if x[4] == searchUser:
            print()
            print(searchUser, "found in the list")
            update_user()
            updateSelection = input("\nInput number of field or press Q/q to return to Menu 3: ")
            if updateSelection == "1":
                newFirstName = input("Input new First Name: ")
                allUserDetails[0][0] = newFirstName
                print(allUserDetails)
            if updateSelection == "2":
                newLastName = input("Input new Last Name: ")
                allUserDetails[0][1] = newLastName
                print(allUserDetails)
            if updateSelection == ("Q", "q"):
                searchUser = input("\nInput username to edit (press 1 to return to Main Menu): ").lower()

    for x in allUserDetails:
        if x[4] != searchUser:
            # Print not found message
            print()
            print(searchUser, "not found")
            continue
    else:
        break
    

CodePudding user response:

Your issue comes from the indexing of the list: allUserDetails[0][0] = newFirstName

This will always update the first index. However, you are trying to update list x: x[0] = newFirstName

The same issue applies to the newLastName

  • Related