Is it possible to endlessly add key:value pairs to a dictionary based upon user input?

Question:

I have a dictionary called "user_database" that holds users, and a variable called "registered_users" that increments as the input is called in a "while True" loop. How can I endlessly add new users to the dictionary as the inputs are entered?
this is what I have, (BTW I am a beginner at python)

user_database = {
    "username": "my_username",
    "password": "my_password"
}
 
registered_users = 1

def register_user(user_database):
    if user_database:
        while True:
            for i in range(3):
                registered_users = i += 1
                username = input("Enter your username: ")
                password = input("Enter your password: ")
                user_database[f'username_{registered_users}'] = username
                user_database[f'password_{registered_users}'] = password
                print(user_database)
                continue
register_user(user_database)

here is the output:

Enter your username: sunshine
Enter your password: sunshine123
{'username': 'my_username', 'password': 'my_password', 'username_1': 'sunshine', 'password_1': 'sunshine123'}
Enter your username: sunshine_2
Enter your password: sunshine555
{'username': 'my_username', 'password': 'my_password', 'username_1': 'sunshine_2', 'password_1': 'sunshine555'}
Enter your username: 

It is not adding A NEW key:value pair on EACH entry, its simply replacing the extra one.
I want to add a new key:pair upon each username & password input entry.

I have tried update() and It did the same thing. Although I may have used it incorrectly.

Asked By: Joi

||

Answers:

Something like this would do what you would want:

user_database = [{
    "username": "my_username",
    "password": "my_password"
}]
 
registered_users = 1

def register_user(user_database):
    global registered_users
    if user_database:
        while True:
            registered_users += 1
            new_user = {}

            username = input("Enter your username: ")
            password = input("Enter your password: ")
            new_user[f'username_{registered_users}'] = username
            new_user[f'password_{registered_users}'] = password
            user_base.append(new_user)
            
register_user(user_database)

In the following, the registered users are saved in a list. In this list, there are dictionaries for each user containing a key for the username and a key for the password, which is entered in the while loop. You would want to find a way to break out of the while loop yourself, otherwise you will keep going on forever. This is simply done by adding a closing condition that executes a break. For good measure, I have added that the variable registered_users is uses the global variable.

Answered By: Lexpj

I don’t see the reason using the for loop, but something like this will work if you are okay with the output :

def register_user(user_database):
    global registered_users
    if user_database:
        while True:
            registered_users += 1
            username = input("Enter your username: ")
            password = input("Enter your password: ")
            
            user_database.append({
                f'username_{registered_users}': username,
                f'password_{registered_users}': password
            })
            print(user_database)

user_database = [{
    "username": "my_username",
    "password": "my_password"
}]
 
registered_users = 1

register_user(user_database)

Make sure that you need to break the while using a condition or something, otherwise it will keep running forever.

The result will look like this :

[{'username': 'my_username', 'password': 'my_password'}, {'username_2': 'sunshine', 'password_2': 'sunshine123'}]
Answered By: SWEEPY

You were going the right way. I would suggest you add usernames as your user_database dictionary’s keys and the passwords (ideally the hashed passwords) be the dictionary’s values. This way it will be really fast retrieving your existing usernames and their respective password, for authentication or other purposes you may have. I rewrote your program like this:

user_database = {
    'janedoe': 'MyPassword123'
}
registered_users = 1

def hash_password(password):
    hashed_password = password # do something to the password
    return hashed_password

def register_user(username, password):
    global user_database, registered_users

    if username in USERS:
        raise Exception('Can't use {username} as username.')

    user_database.setdefault(username, hash_password(password))
    registered_users += 1

def main():
    while True:
        username = input('What is your username? ')
        password = input('What is your password? ')

        register_user(username, password)
        print(f'Current users count: {USERS_COUNT} {USERS.keys()}')

        command = input('End program? [Y/n]')
        if command.strip().lower() in ['', 'y']:
            break

Just call the main function in the program, execute it, and you can start registering users.

Hashing (A little introduction)

I know this is just a little project for you to learn, but this is just a bit of advice for you to learn even more. I hash the password using the function hash_password in order to make your user_database more secure. See this link so you can understand what is password hashing. You would have to hash every password upon users registration, the process to check for correct password would be to verify the raw password passed by users with the stored hash. There are many tutorials that show how to handle all that; it’s a simple process.

Answered By: ccolin
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.