Python Forum

Full Version: Pandas dictionary dataframe help
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am developing a little program that stores user credentials in a dictionary and transfer them in a Pandas dataframe. Since the credentials are stored in a nested dictionary that begins with the username entered by the user, i dont know how to index the nested dictionary. Returns this error:
Error:
Traceback (most recent call last): File "profile_creator.py", line 29, in <module> add_dict(username,password,email,phone_number,notes) File "profile_creator.py", line 6, in add_dict user_df = pd.DataFrame(credentials[0]) KeyError: 0
import pandas as pd

def add_dict(username,password,email,phone_number,notes):
    credentials = dict()
    credentials[username] = {"password" : password, "email" : email, "phone_number" : phone_number, "notes" : notes}    
    user_df = pd.DataFrame(credentials[0])
    print(user_df)
Post code in code tag not image,same as you dos with error message.
Try change to.
user_df = pd.DataFrame(credentials['username'], index=[0])
Edit:
Ok i see you change it.
(Jun-18-2021, 08:24 PM)snippsat Wrote: [ -> ]Post code in code tag not image,same as you dos with error message.
Try change to.
user_df = pd.DataFrame(credentials['username'], index=[0])
Edit:
Ok i see you change it.

I can't know what does the user enter as username because it is stored into a variable.
Error:
Traceback (most recent call last): File "profile_creator.py", line 29, in <module> add_dict(username,password,email,phone_number,notes) File "profile_creator.py", line 6, in add_dict user_df = pd.DataFrame(credentials['username'], index=[0]) KeyError: 'username'
Try this,i see your username in not just a string but a variable that get as argument from function.
user_df = pd.DataFrame(credentials[username], index=[0])
Basic test to see if this work.
import pandas as pd

credentials = dict()
credentials['username'] = {"password" : 123, "email" : 'test@org', "phone_number" : 55667788, "notes" : 'hei'}
user_df = pd.DataFrame(credentials['username'], index=[0])
print(user_df)
Output:
password email phone_number notes 0 123 test@org 55667788 hei
(Jun-18-2021, 09:16 PM)snippsat Wrote: [ -> ]Try this,i see your username in not just a string but a variable that get as argument from function.
user_df = pd.DataFrame(credentials[username], index=[0])
Basic test to see if this work.
import pandas as pd

credentials = dict()
credentials['username'] = {"password" : 123, "email" : 'test@org', "phone_number" : 55667788, "notes" : 'hei'}
user_df = pd.DataFrame(credentials['username'], index=[0])
print(user_df)
Output:
password email phone_number notes 0 123 test@org 55667788 hei

It does work but basically is not what I want to do. The dictionary key should be the same string that the user entered and in order to do that I use a variable, but once it is stored I don't know how to refer to it and so access it.