How can I create a multi-value dictionary? - python

I have user info from a SQL Server - a username and password -
and now I want to create a dictionary
{ID : password}
but if I have more then one it just saves the last one I put in
for i in (cursor.execute('select * from Person')):
idNameDict = {i[0]:i[3]}
I want to do it this way so it would be easier for me to do check if the based on the ID that the password input would be correct because right now and it seems to long
def logIn(userName,userPassword):
userID=[]
global p
lbl = Label(root)
lbl.grid(row=5,column=1)
for user in (cursor.execute('select * from Person')):
p = Person(user[0],user[1],user[2],user[3])
userID.append(p)
for id in userID:
if userName == id.ID:
if userPassword == id.password:
userPage(root,userName)
else:
lbl.config(text= "Invalid Password")
else:
lbl.config(text= "Invalid User Name")

Your current code doesn't work properly because you declare the dictionary from scratch in each iteration. You need to do it in the following way:
idNameDict = {}
for i in (cursor.execute('select * from Person')):
idNameDict[i[0]] = i[3]

Related

DB values are not in global scope

Usage
I am using the replit browser IDE for this project. Also, I am using replit's database for this project.
Problem
So as you can see, in the code below, I am asking the user to log in or Sign up, while saving the user's data of money, deposits, inventory in a key-value pair into the database of replit. It is simple to do that, first I import replit:
from replit import db
And then I assign the key-value pairs to a list like:
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
# the password, money, inventory, allowed deposit, deposited, and boolean for working or not, respectively.
But to actually uses the user's stats saved to their value pair, I have to make the username available in all places in the code. Rather I assigned them to variables:
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
But despite doing that, I get errors that "user name is not defined" and "self.inventory is not defined". I am getting the values using the list as you will see below
The Real Question
My real question is that how can I make the variables, that I have put up, have the values of the list that I have assigned to the value pair of the user's name and make it work globally. Because later in the code, I append to the self.inventory list which is in the value pair list assigned to the user.
Code
Here is a portion of the important code that I am using.
class Game:
def __init__(self, username):
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
def database(self):
enter_game = input("Do you want to [1] Login\n[2] Signup:\n>")
while enter_game == '1' or enter_game == '2':
if enter_game == '1':
username = input("Enter user name: ")
password = input("Enter password: ")
if username in db.keys():
if db[username][0] == password:
print("Loggedd In")
break
else:
print("Invalid Username, Password")
break
if enter_game == '2':
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
break
Also, the project is literally massive, so rather, I have attached a link to go to the real code(The code that is used here is in the gameplay.py file):
Click here to go to the repl with the code.
Or if that doesn't work, click here:
https://replit.com/#OldWizard209/Life-SIMULATOR-In-Development-2#gameplay.py

Get username from previous def into another def with if statement

I have some code where I'd like to use the inputted username again in another def, but it doesn't generate anything. I get a username with the following code without issues (s_print is a slow print for reference):
def input_username():
username = input()
user = username
s_print('Hello {}!'.format(user))
return user
input_username()
Then I have a def a bit later on in the code with various if statements:
def options_input():
if option == '1': etc.
elif option == 'Bye':
end_user = input_username()
s_print('Goodbye {}!.'.format(end_user))
else: etc.
options_input()
I want to get the username inputted in def input_username to be reprinted in the def options_input elif option == 'Bye' but it just generates blank with no error code/message, like it's looping continuously through code. What is going wrong?
input_username() is a function
when you call a input_username() you need to save it in a variable to use it later
username = input_username()
and then later in options_input()
end_user = username
this line:
end_user = input_username()
asks you to input username again it doesent have old one

How do I store the values into this dict so that in the next iteration it would work?

I'm not sure how to store the values taken from the user input (to generate new username and password) and store it in the iass dict, so in the next iteration it would work:
iass = {}
class login:
def __init__(self):
pass
def passcheck(self):
for key, value in iass.copy().items():
if self.username == key and self.password == value:
print("Granted Access")
else:
A = str(input("Enter Desired Name: "))
B = str(input("Enter Desired Password: "))
iass[A] = B
A1 = login()
A1.username = str(input("Enter Username: "))
A1.password = str(input("Password: "))
A1.passcheck()
Your usage of a class/object is a little strange. Usually one would create a class for something that represents an object (a noun) in the real world. In your application, this might be User.
Login would be a method in that class.
Your method passcheck is also a bit strangely constructed. As you've just asked for the input of Username and Password, you can reuse these at all times. You don't need to ask them again. I'd recommend you to pass username and password as parameters in the login method, rather than setting them directly as parameters. Your code could look somewhat like this
iass = []
iass.append({'myuser': 'mypwd'})
class User:
def __init__(self):
pass
def login(self, username, password):
for key, value in iass.items():
if username == key and password == value:
print("Granted Access")
return
# User not found, so we're adding him
iass.append({username: password})
A1 = User()
username = str(input("Enter Username: "))
password = str(input("Password: "))
A1.login(username, password)
Note: didn't run this in the python parser. might have some issues :-)
Please run pylint on your code.
It will uncover bugs for you before you run it.
It will improve the code readability. This helps everyone: yourself and others who will read your code.
Code changes:
Remove the iass.copy() call. It was unnecessary; though not creating a bug.
To make the code "work" you need to initialize iass with a key and value:
iass = {"ding": "dong"}
Remove the else: block. That is causing an extra prompt which is only confusing and would be considered a bug.
Now when the user enters a username, password "ding" and "dong" your check will "pass".

How to create a unique alphanumeric id each time and ensure it doesn't exist in my existing list using python?

I need to assign a unique name that contains the word 'user' and a certain random numbers to a user. Something like user32944, user80890 etc. So I write a program something like this
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
user_name = ""
while(True):
if user_name not in user_list:
user_name = "user" + str(random.random() * 100000).split(".")[0]
break
print(user_name)
But if I deliberately set the user_name to something that already exists in the list, my program doesn't exit the loop and the program hangs.
What am I doing wrong?
You only perform a action when the generated username is not in the list, but you don't do anything when the username is in the list. And therefore you don't exit the while loop and the program will hang.
The following code sample does what you want. Although i recommend you to explore the uuid package in python.
import random
user_list = ["user32944", "user60690"] # essentially this list is what I retrieve from some database
def generateRandomUsername():
randomNr = random.randint(1,3)
if randomNr == 1:
return "user32944"
else:
return "user" + str(random.random() * 100000).split(".")[0]
def getRandomUniqueUsername():
while(True):
username = generateRandomUsername()
if username not in user_list:
print('Created user \'%s\'' % username)
return username
else:
print("Username \'%s\'already exists, generating new one" % username)
def printUsernameList():
for username in user_list:
print('Username: %s' % username)
#Create 4 random usernames
for i in range(4):
username = getRandomUniqueUsername()
user_list.append(username)
print('Printing user_list...')
printUsernameList()
That will never exit the loop because you are never satisfying the IF condition and there is no conditional expression on while too, you gave True in while condition -> which means it loops infinitely.
So if you do not satsifying the IF condition then write a logic what you would want to do incase IF does not get statisified and then break out of the loop.
And if you want guid with just random alphanumeric ids, then use uuid package in python.

Unable to take input from user in python

I have a made a function in which I am taking value from user and want to send that value to another function for verification. But the problem is that I am unable to take value from user because that part of code is not running. The interpreter takes me directly to else part of the while loop. Here is my code:
from userAccountDatabase import *
FirstName = ""
LastName = ""
dateOfBirth = ""
userDetails = []
def userDetailsValidation(fieldvalue, fieldName, database):
for entry in database:
if fieldName in entry and entry[fieldName] == fieldvalue:
print("correct value")
return True
else:
return False
def userInputs(FirstName, LastName, dateOfBirth):
FirstName = str(input("Enter First Name").upper()) # This part of code is not running
while True:
if(userDetailsValidation(FirstName, "FirstName", userAccountDetails)) == True:
userDetails.append(FirstName)
break
# directly take me to this
else:
print('Enter valid First Name')
FirstName = str(input("Enter First Name").upper())
userInputs(FirstName, LastName, dateOfBirth)

Categories

Resources