A project in a coding class I'm taking asks students to finish the code for a password saver with a number of options and a menu. The part I'm having difficulty with is printing a password based on the website associated with it.
Passwords are saved in a list like so:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
What I'm attempting to do is find the address of an item within this list, inputted by the user, and print the item directly after it. The user will be asked to input a website and the following item in the list (the password) will be printed.
However, for testing purposes, I also need to check to see if a password for the website in question is in the "passwords" list.
if passwordToLookup in passwords:
print(passwords.index(passwordToLookup))
For some reason, this always returns "False." Is this because the list I'm searching is encrypted? If so, how can I search in this list for a specific item? How could I print the second item in the list following the website?
Using dictionaries
# convert list into dictionary
d = dict(tuple(passwords))
try:
d[passwordToLookup]
except KeyError:
# what to do if no password available
else:
# what to do if available
or use default get method of dictionary
return d.get(passwordToLookup, default=None)
Without dictionaries
values = list(zip(*passwords))
try:
the_password = values[1][values[0].index(passwordToLookup)]
except ValueError:
# what to do if no password available
else:
# what to do if available
You can loop through the list and check for the website:
for elem in passwords:
if passwordToLookup in elem:
print # elem[0] for the website or elem[1] for the password
not sure why you are trying to print the index but you can also use passwords.index(elem) if you want it.
Your problem is that you are currently only looking in passwords which is a list of lists, but you need to iterate through passwords and test the individual lists within it. You could use something like this
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
def getPasswordIndex():
for list in passwords:
if "CoIushujSetu" in list:
return list.index("CoIushujSetu")
else:
print(False)
print(getPasswordIndex())
#returns False then 1 so it's the second item in the second list """
print(passwords[1][1])
#prints "CoIushujSetu"
Use a dictionary (key: value pairs) and your code will be as simple as this:
passwords = [["yahoo","XqffoZeo"],["google","CoIushujSetu"]]
pass_dict = dict(passwords)
site = input("Insert site: ")
if site in pass_dict: # searching only in keys
print(pass_dict[site]) # print value of that key
What you need to do is iterate through the list something like this :
def ifPassExist():
for password in passwords:
if passwordToLookUp in password:
return passwords.index(password)
Related
I am a newbie programmer so sorry if any of these are dumb questions. This class is my first ever programming experience.
I am trying to create a search function that will search a dictionary and upon invoking it would give you all the keys from the dictionary separated by a '/t'. I then want to make the function prompt the user to enter a key. When the key is in the dictionary the key is supposed to give you the the information from the dictionary. When the key is not in the dictionary I want to create an output message such as "That student is not in class".
I have created a function off of my dictionary which will simply print all the information from the dict if you enter the correct key; however it is not off of the search function. I know I am lacking in having a true/except block that works, and a while true and return function.
I need to make (searchStudentDict) or use a true/except block or while true or a return statement. Below is my incorrect code trying to do this problem within it's boundaries.
def searchStudentDict():
for i in dctStudents.keys():
try:
while true:
except:
print('That student is not in class')
return
searchStudentDict(dctStudents)
I would be forever grateful to anyone who could edit this and get this to actually show up in the code block I've spent more time formatting than on my question. It isn't taking any of the indents i made
The expected output is the keys below tab separated such as
7373'\t'8274'\t'9651'\t'2213'\t'8787'\t'9999
*using python create tab here since the physical tab key will not tab them apart.
dctStudents = {
'7373':['Walter White',52,'Teacher'],
'8274':['Skyler White',49,'Author'],
'9651':['Jesse Pinkman',27,'Student'],
'2213':['Saul Goodman',43,'Lawyer'],
'6666':['Gus Fring',54,'Chicken Guy'],
'8787':['Kim Wexler',36,'Lawyer'],
'9999':['Tuco Salamanca',53,'Drug Lord'] }
One possible solution that may work for you:
#First print all the keys separated by tabs
print('\t'.join(someDict.keys()))
#Infinite loop
while True:
#read user input
userinput = input("Enter a key: ")
#the method get will try to get the key, if no matches will display the string passed.
print(someDict.get(userinput, "No key matches the dict"))
You can use * unpacking with sep argument of print:
print(*dctStudents, sep='\t')
When inside a function, this looks like:
def searchStudentDict():
print(*dctStudents, sep='\t')
...will print keys of the dictionary separated by tab space.
You can do following to retrieve value of a key if its present or throw a message if it's not present:
def searchStudentDict():
print(dctStudents.get(input('Enter key: '), 'That student is not in class'))
Something like this will display all of the keys from the dictionary separated by tabs
print('\t'.join(someDict.keys()))
If you want to search the dictionary for a specific key and print out the value that corresponds to that key while guarding against exceptions, the basic example is one way of doing so:
def searchStudentDict(someDict):
targetKey = ""
# End at user's request
while True:
targetKey = input("Enter a student ID (\'q\' to quit): ")
if targetKey.lower() == 'q':
break
# Search for it in dictionary using try-except (handle exceptions)
try:
print("Student {} Info: {}".format(targetKey, someDict[targetKey]))
except KeyError:
print("No information exists for this student")
except:
print("Some unknown error occurred")
# Handle how you see fit
print('Ending search...')
def main():
studentDict = {
'7373' : ['Walter White',52,'Teacher'],
'8274' : ['Skyler White',49,'Author'],
'9651' : ['Jesse Pinkman',27,'Student'],
'2213' : ['Saul Goodman',43,'Lawyer'],
'6666' : ['Gus Fring',54,'Chicken Guy'],
'8787' : ['Kim Wexler',36,'Lawyer'],
'9999' : ['Tuco Salamanca',53,'Drug Lord']
}
# Print the existing students
print('\t'.join(studentDict.keys()))
# Perform search
searchStudentDict(studentDict)
if __name__ == "__main__":
main()
And the corresponding output would be:
$ py -3 search.py
7373 8274 9651 2213 6666 8787 9999
Enter a student ID ('q' to quit): 8274
Student 8274 Info: ['Skyler White', 49, 'Author']
Enter a student ID ('q' to quit): 9999
Student 9999 Info: ['Tuco Salamanca', 53, 'Drug Lord']
Enter a student ID ('q' to quit): 1111
No information exists for this student
Enter a student ID ('q' to quit): q
Ending search...
Typically, you would not want to handle a search inside a dictionary this way (using try-except). A simple if statement or the use of get should suffice but if you require the use of a try-except, you would need to guard against the KeyError that would be raised if you try to access a key that does not exist. Hope this helps.
Working on this for learning experience. The 3 ideas below I came up with
A) User creates a profile so I have a dictionary for fname and lname.
B)Then I randomly generate userid add that to a list. This list only contains random user id that I will user later eg: userid012,userid89
C) I assign A and B in a new dictionary. Output looks like this:
used_id user3
profile {'lastname': 'jon', 'firstname': 'jme'}
problem: I only see the last values user id and names. If I have more than 2 entries, I do not see the 1st ones. Helpful hint would be really helpful.
Thank You.
import random
print('Enter choice 1-3:'),'\n'
print('', '1-Create new profile','\n',
'2-Update existing profile','\n',
'3-Delete a profile')
#global variables
choice=int(input())
user_directory={}
#Dictionary function that takes fst and lst name and puts in a dict:
def new_profile():
new_profile={}
fn=input('First name:')
new_profile['firstname']=fn
ln = input('Last name:')
new_profile['lastname'] = ln
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
#Generates a random user id which we will assign to a user created above
def user_id():
uid_list=[]
user_id='user'+str(random.randint(0,101))
uid_list.append(user_id)
if(user_id in uid_list):
uid_list.remove(user_id)
user_id = 'user' + str(random.randint(0, 101))
uid_list.append(user_id)
return user_id
#This dictionary will have user id and associate created new_profile
def addToDict():
#user_directory={} unable to use this making it global
user_directory['used_id']=user_id()
user_directory['profile']=new_profile()
for key,value in user_directory.items():
user_directory[key]=value
return user_directory
if(choice==1):
# myuser=addToDict() this appraoch did not work
#addToDict>> adding it here will not get this option in while loop, put inside while
while True:
addToDict()
print('Add another entry?')
choice=input()
#Put the line below to see if number increases
print('Current', len(user_directory)-1)
if(choice!='stop'):
continue
else:
break
for k,v in user_directory.items():
print(k,v)
Bad indentation in the last line of new_profile(). The return is running on the first iteration. Try:
for k,v in new_profile.items():
new_profile[k]=v
return new_profile
Btw, you don't seem to be following most conventions/standards in Python. Take a look at this simple tutorial about PEP, the official style guide. This way you can make better looking code and we can help faster :)
Your code contains a couple of bugs. I can only guess what you want to do. Lets start with the obvious: The function addToDict() should probably add a new user to the dictionary.
What you usually want is to have a dictionary which maps a user_id onto a profile:
def addUserToDict(user_dictionary, user_id, profile):
user_directory[user_id] = profile
And then in the input loop below you call this function with your dictionary, a new user id and a new profile.
A second bug is in user_id(): You always return a list with one new element, with a new random user id. And you always discard the first generated user id and then you add a second one.
I'm trying to create a friend dictionary in which I can add a friend and put there his info.
I want to use the friend's name as the key, two numbers, two emails and information about where he lives.
My problem is that my program crashes when asking for the numbers and for the emails, I dont know what i did wrong.
I used the append, function because the numbers of each friend are saved in a list. I dont want a new program I want to repair mine so I can understand why it's failing.
The other thing I'm trying to do is to not print the empty dictionary that im creating at the end, its a list with dictionaris in it (each friend is a dictionary), so i guess i should say to print the list from the position 1 to the end but i guess there is a better way, here I post my code, the error is when i ask for the first and second phone and mail.
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
for i in range(2):
contact["phone"][i]=input("phone: ") #Here it crashes
for i in range(2):
contact["mail"][i]=input("mail: ") #Here too
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
You need to create a list for the phone and email, then append to it:
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
The problem with your solution is that you try to add value to something which is not present.
When you do contact["phone"]. This creates a key inside dictionary contact. {"Phone":}
But the problem is you do contact["phone"][i]. So ith element is searched in this key. Which is not present. Hence you get error. So you first need to add list to this dictionary. Then only you can add multiple numbers
def add_contact(friends):
contact = {}
contact["name"]=input("name: ")
contact["phone"] = []
contact["mail"] = []
for i in range(2):
contact["phone"].append(input("phone: "))
for i in range(2):
contact["mail"].append(input("mail: "))
contact["street"]=input("street: ")
contact["housenum"]=input("housenum: ")
contact["cp"]=input("cp: ")
contact["city"]=input("city: ")
friends.append(contact)
friends = [{"name":[{"telf":[0]*2},{"mail":[0]*2},
{"street":"","housenum":"","cp":"", "city":""}]}] #This is the list im creating to fill it with friends information, the first dictionary in the list is an empty dictionary which i dont want to print.
add_contact(friends)
print(friends)
I am trying to make a program where my students will enter their ID numbers so I can (later in the code) automate sending attendance, and record who has handed in homework and who hasn't so emails can be sent to parents. I have everything else made, but I cannot get the inputting of student ID's working.
What I am trying to do:
1)make sure that their input is 7 characters long
2)check their ID exists in 'fakeID'
2a)have the students confirm their name from 'classNames' with a y/n.
2b) append their name into inputIDList
3) if the input is == to 9999990 exit the loop.
What it is doing:
1) asking for input
2) moving on in the code and not looping
3) not appending inputIDList
I think I am making this too complicated for my current skill level.
edit:
The loop is not checking to see if the inputed ID is in my fakeID list.
Also, it isnt looping for, so once the input is entered it continues on with the next set of code.
edit2:
updated code that works. :D
fakeID = ['1111111','1111112','1111113','1111114','1111115']
classNames = ['name1', 'name2', 'name3', 'name4', 'name5']
toplist = list(zip(fakeID, classNames))
inputIDList =[]
def inputID():
while True:
id = input('Please enter your student ID and hit Enter')
if id == '9999990':
print('Done')
break
if id in fakeID:
inputIDList.append(id)
print('recorder')
continue
if id not in fakeID:
print('I do not know this ID. Please try again.')
continue
If I understood your problem correctly then I suppose that you are trying to save the ID numbers of the students in inputIdList and then check whether a particular ID is in inputIdList or not. In the last if condition you are trying to compare a List type object with a String type object which will definitely throw an TypeError. Instead define the following function and call it in the if condition.
def check_list(id):
try:
inputIdList.index(id)
return True
except TypeError:
return False
list.index() method tries to find the element in the list and returns the index number of the element. And then call this function in your if condition.
if check_list('9999990'):
print('done')
#break
Furthermore there is no need to assign inputIdList = [""] if you have already intialized it to inputIdList = [].
If the problem persists please send the output in the thread.
Here is something to get you started:
fakeID = {'1111111','1111112','1111113','1111114','1111115'}
while True:
id = input('Please enter your student ID and hit Enter')
if id == '9999990':
print('Done')
break
if id not in fakeID:
print('I do not know this ID. Please try again.')
continue
as Abarnert said you need to restructure your method. but I think I found where you were stuck.
after you have checked for the length of input number, you should check whether that number matches any fakeID,and get the corresponding class name.
so your first loop should be like this
for i in toplist:
rather than
for i in [i for i,x in enumerate(inputIDList) if x == fakeID]:
since inputIDList is empty your program will not go inside the loop. And inside the changed loop you should be checking
if s == fakeID
This is the limit of what I could understand of your desired operation. But if you need further help just ask.
cheers.
Write a program that ask the user to enter an integer representing the number of items to be added to the stock. For these items, the program should then ask for the item barcode number and name, add them to a dictionary and print them.
Why is my code not working as expected?
size=input("Enter size of list")
names=[input()]
code=[int(input())]
for i in size:
print("Enter name and code")
names.append(input())
code.append(int(input()))
dict={names[i]:code[i]}
print(dict)
This a functioning version of your code:
size = input("Enter size of list")
names = []
code = []
for i in range(int(size)):
print("Enter name and code")
names.append(input())
code.append(int(input()))
d = dict(zip(names, code))
print(d)
Among the errors that needed fixing:
Only use input() in your for loop when you need the data.
i needs to cycle through range(int(size)) rather than a string input.
Create the dictionary from your lists at the end via zip.
Do not name variables after classes, e.g. use d instead of dict.