Home > front end >  Python: Parsing List of lists
Python: Parsing List of lists

Time:04-01

In Python I'm attempting to create a login page that draws stored data from a Google Sheet for use in Streamlit Authenticator. Streamlit Authenticator authenticates logins by accessing a list container with usernames, passwords, and screen names, as below:

username = ['johndoe', 'janedoe']
password = ['123', '456']
names = ['John Doe', 'Jane Doe']

The application I'm developing runs on the cloud, and I'm storing the user data in a Google Sheet, structured like so:

username, password, names
johndoe, 123, John Doe
janedoe, 456, Jane Doe

Using pysheets and the get_as_df operation, I'm seeking to pull the data to fill the containers for Streamlit Authenticator. However, when I pull a with pysheets the individual cells come back as separate lists, as in this example for the username column:

import pygsheets
import pandas as pd

gc = pygsheets.authorize(service_file=local_file) #for Google Sheets API authentication 

sh = gc.open('users') # Google Sheet name
wks = sh0[0] # Worksheet number
database_length = wks0.get_all_values(include_tailing_empty_rows=False, include_tailing_empty=False, returnas='matrix') # for finding the number of filled rows in sheet
end_row = str(len(database_length))
usernames_grab = wks0.get_as_df(has_header=False, index_column=0, start='A2', end=('A' end_row0), numerize=False) # grabs cell data as dataframe
usernames_list = usernames_grab.values.tolist() # converts dataframe to list
print(usernames_list)

Which returns:

[['johndoe'], ['janedoe']]

I attempted then to setup the Streamlit Authenticator accordingly:

username = usernames_list
passwords = password_list
names - names_list

But when loading the script I receive the following error: AttributeError: 'list' object has no attribute 'encode' I'm guessing I can't pass a list of lists in this manner? Any suggestions on how to proceed?

CodePudding user response:

This is because your username is a list of lists, not a list of strings.

All you need to do is extract the string from the inner list.

>>> username = [lst[0] for lst in usernames_list]
['johndoe', 'janedoe']

If your usernames_grab dataframe has column names, you could also just do:

username = usernames_grab["username"].to_list()
  • Related