How to delete one value of keys from dictionary? - python

I'm trying to delete a specific input of user using del function but it deletes the whole key values below it
for account3 in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
userinput = input('Account Name you want to delete: ')
for account4 in accounts:
if userinput == account4["Name"]:
userinput = input('Re-enter name to confirm: ')
for account5 in accounts:
if userinput == account5["Name"]:
del account5["Name"], account5["Username"], account5["Password"]
print('Deleted Successfully!')
menu()
break
After the user confirms the deletion, it deletes all values in the dictionary and gives a key error: "name". Is there any way to delete only the information given by the user?

Setting the values to None is what you want instead of deleting the entries.
Replace the del line with this.
account5["Name"], account5["Username"], account5["Password"] = None, None, None

To avoid having to loop through the list multiple times to find the matching account, I suggest building a dict that maps the name to each account, and using accounts.remove() to remove the account.
accounts_by_name = {account["Name"]: account for account in accounts}
for account in accounts:
print("\t ", account3["Name"].ljust(25), account3["Username"].ljust(27), account3["Password"])
name = input("Account name you want to delete: ")
if name not in accounts_by_name:
continue
if input("Re-enter name to confirm: ") != name:
continue
accounts.remove(accounts_by_name[name])
menu()
break

Related

How do I iterate over every value in a key where the value is the instance of a class?

I want to iterate over every instance i stored as a value to a number stored as a key in a dictionary. Where if I were to make an account named jason, it would be assigned 1, then if I were to make a new one, it would be assigned 2. That part is already done but the iteration part is very confusing for me. Why does it only go through the first key value pair in the dictionary?
Ps: I am new to oop this is my first oop thing where i did not follow any guides so that id would actually learn. Thank you <3
class Bank:
serialnum = 0
username = ""
email = ""
password = ""
bal = 0
def __init__(self,count):
self.serialnum = count
self.username = input("What's your username? \n")
self.email = input("What's your email? \n")
self.password = input("What's your password \n")
self.bal = input("How much balance do you have \n")
def withdraw(money):
self.bal= bal-money
print (bal)
global count
count = 0 #counts and is the serial num
accounts = {} #accounts dictionary
def accountcreate(): #gets called when account does not exist
global count
while True:
serial = int(count)
account = Bank(count)
print("The serial is {}".format(count))
count += 1
accounts[serial] = account
print("Your account has been created, please use the username registered. ")
break
accountaccess()
def accountverify(name):#if accountverify returns false, prompts the accountcreate function
username = ""
start = 0
balance = 0
if 0 in accounts: #essentially means if the first account has been made
for key in accounts: #loops through accounts in accounts dictionary
#sets the keys gotten and sets the un to the username attribute of every key
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",(getattr((accounts[key]),"username")))
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
else: #makes first account
ask1 = (input("Account does not exist, would you like to make an account? Yes or No \n")).lower()
if ask1 == "yes":
makeAccount = accountcreate()
def accountaccess(): #accesses account
ask = (input("Do you want to access an account? Yes, or no. "))
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
loop = True
while loop == True: #mainloop
ask = (input("Do you want to access an account? Yes, or no. \n")).lower()
if ask == "yes":
getname = (input("What is your username? ")).lower()
ver = accountverify(getname)
loop = False
The replit link
It would also be helpful to know how to store the username as the name of the value since what is shown there is incredibly cryptic
In this image, every new username registered is a new instance of the Bank class. But the for loop only goes on the first one
The part of your code that is causing the issue is
if hasattr((accounts[key]),"username") == name:
print("logged in as ", name, "Password is \n",
(getattr((accounts[key]), "password")),
"Account balance is ", getattr((accounts[key]), "bal"))
The return from hasattr is a boolean and cannot be compared to name.
Try changing it too
if hasattr(accounts[key],"username"):
if accounts[key].username == name:
....
Also your use of getattr() is incorrect and unnecessary since you can simply access those attributes directly.
For example:
account = accounts[key]
print(account.username)
print(account.password)
print(account.bal)
with all of that in mind your accountsverify function should look more like this:
def accountverify(name):
start = 0
balance = 0
if 0 in accounts:
for key in accounts:
account = accounts[key]
if account.username == name:
print(f"logged in as {name} Password is \n {account.password} \n Account balance is {account.bal}")
action = input("What do you want to do? \n -Withdraw \n -Deposit \n -Transfer \n -Make another account \n")
if "make" in action:
print("Making another account... \n Please enter your credentials")
makeaccount = accountcreate()
else: #if username does not exist
print("First item in list is ",account.username)
print(accounts)
accountask = input("Account does not exist, make a new account? Yes or No \n").lower()
if accountask == "yes":
makeAccount = accountcreate()
As far as making the Bank class print the accounts name you just need to overwrite the __str__ method.
class Bank:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name

How to check if only a part of a variable is next to a string in Python?

I'm trying to get my code to check if a word is already in the document. However when choosing a variable (username) that happens to share the same letters going to the right as the preexisting one in the file, it thinks that the name is taken. For example, if abcdefg was in the file, if I was to right defg or fg or g, it would think the username was taken.
def register():
print("━━━━ACCOUNT CREATION━━━━")
username = input("Create Username: ")
with open("Login.txt", "r") as loginfile:
if (username+",") in loginfile.read():
print("Sorry, but that username is taken.")
choice = input("Try again with a new name? (Y/N)")
choice = choice.upper()
My case:
Say I had the name, Joe which is already in the file. If I tried to make a username that is just e, then it would think it is Joe, as it is looking for the e, next to a comma.
Anyway to fix this? Thanks!
This should work
with open('login.txt', 'r') as LoginFile:
# the split function splits a string to a list on mark
Data = LoginFile.read().split(" ,")
if username in Data:
# .....
if this isn't what you want try this built-in module :
https://docs.python.org/3/library/re.html
def register():
print("━━━━ACCOUNT CREATION━━━━")
# read the names from the file
with open('Login.txt', 'r') as f:
names = f.read().split(',')
username = input("Create Username: ")
for name in names:
# check if any names end with this name have been created
if name.endswith(username):
# found
print("Sorry, but that username is taken.")
# we want to keep ask the user to select if
# they enter something other than Y/N
while True:
# ask for the option
option = input("Try again with a new name? (Y/N) ")
# try again, we just rerun this function
if option == 'Y':
register()
# don't ask any more
break
elif option == 'N':
# exit if user chooses N
break
# if the user chooses something else, continue
# the loop and keep asking
# if no names end with username, goto else
break
else:
# name available, save it to the file
print("Name created successfully:", username)
new_names = names + [username]
with open('Login.txt', 'w') as f:
f.write(','.join(new_names))
I have tested it, please try and see if it works for you.

Nea login part loop?

im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.

if x in [list] iterator

def new_user() -> str:
users = []
print("Welcome to The 'Create New User' Interface")
sleep(0.5)
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
if x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
else:
users.append(x)
print("Your Account Access Name is: " + str(x))
So I'm not sure how to word this question but I have this block of code and as you can see I want to check if the user inputted name already exists, and if it does it'll prompt for a new name and add it to the list, and if it doesn't already exist, it'll add it to the list, but there's a way around this, if the list already contains a name and the user inputs that same name the if x in users: code will run and when prompted to enter another name, if they enter that same name, it wont recognize that it already exists and add it to the list either way, how can i prevent this?
To get valid user input wrap the request in a loop and when you have valid input break out, e.g.:
print("Enter Name to Use for Account Access")
print("*Name is Case Sensitive to Access Account*")
while True:
x = input("Enter a Name: ")
if x not in users: # Valid input
break
print("That User Already Exists!")
users.append(x)
print("Your Account Access Name is:", x)
Solution
users = []
print("Welcome to The 'Create New User' Interface")
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
while x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
Simply just changed your if loop to a while loop that will continue until a unique name is given.
Suggestions
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = '' #now users can not enter a empty user_name
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
for i in range(0, len(users)): #different loop to enable use of lower()
while user_name.lower() == users[i].lower(): #removes need for unique cases
print("That User Already Exists!")
user_name = '' #again stopping empty fields
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
users.append(user_name)
print("Your Account Access Name is: " + user_name)
For start we can create a loop that will reject any blank user_name.
Next we can use .lower() when checking to see if user_name exists in users[]. By doing this we can preserve the unique case format the user wants to use to store their name(perhaps for display purposes) but at the same time we can check to see if user_name already exists regardless of case format.
Cleaning it up we can go with something like this:
def ask_user(message=''): #create function to check for blank inputs
user_name = ''
while not user_name:
user_name = input(message)
return user_name
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = ask_user("Enter Name to Use for Account Access: ")
for i in range(0, len(users)):
while user_name.lower() == users[i].lower():
print("\nThat User Already Exists!") #newline for clarity
user_name = ask_user("Enter Name to Use for Account Access: ")
users.append(user_name)
print("\nYour Account Access Name is: " + user_name) #newline for clarity
Here I created ask_user which handles blank inputs. Then added a \n in a few spots to help with readability.
Output
(xenial)vash#localhost:~/pcc/10$ python3 helping.py
Welcome to The 'Create New User' Interface
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: vash
Your Account Access Name is: vash
Enter Name to Use for Account Access: VASH
That User Already Exists!
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: p0seidon
Your Account Access Name is: p0seidon
Enter Name to Use for Account Access: P0SEidoN
That User Already Exists!
Hope this helps!

Nested list indexing

Trying to create program to answer this question:
[ ] The records list contains information about some company's employees
each of the elements in records is a list containing the name and ID of an employee.
Write a program that prompts the user for a name and return the ID of the employee if a record is found
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
This is my code, so far:
ui = input('Enter employee name: ')
for row in records:
if row[0] in ui:
print(row[1])
else:
print('Employee not found!')
ui = input('Enter employee name: ')
I cannot seem to find a way to check if 'ui' is in the records list.
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
user_name = 'colette' # User input
for i in range(0,len(records)):
# Here I make User name and Name in Recored in lower case so it can match perfectly
if user_name.lower() in records[i][0].lower():
print(records[i])
else:
print("employee not found")
Associate the else block with the for loop instead of the if statement
ui = input('Enter employee name: ')
for row in records:
if row[0] == ui:
print(row[1])
break
else:
print('Employee not found!')
But, if you convert the nested list to a dict, it would be much easier to get the 'id'
ui = input('Enter employee name: ')
d = dict(records)
print(d.get(ui, 'Employee not found!'))
You can use list comprehension to do it -
[i for i in records if ui in i]
This will give you a list of list of employee you are trying to find else empty list.
For ex-
ui = 'Colette'
O/P -
[['Colette', 22347]]
You could do something like -
ui = input('Enter employee name: ')
found = [i for i in records if ui in i]
if found:
for emp in found:
print(emp[1])
else:
print("Employee not found")
This should take care of it, Do keep in mind when comparing two strings, python doesn't automatically convert uppercase to lowercase so its important if you intend to compare a string that you convert both the string in either lower or uppercase
records = [['Colette', 22347], ['Skye', 35803], ['Alton', 45825], ['Jin', 24213]]
ui = str.lower(input('Enter employee name: '))
names_to_compare=[t[0].lower() for t in records]
if ui in names_to_compare:
print(records[names_to_compare.index(ui)][1])
else:
print("Employee not in records")

Categories

Resources