Need to define dictionary without making changes to it - python

I am trying to do a password saver, where users can insert a password and it will save to a computer. I started with
password = str(input("What is your password that you want to save?"))
url = str(input("Which is the site that you want your password to save to?"))
password_saved = {url : password}
with open('password_saved', 'wb') as password_saved_file:
pickle.dump(password_saved, password_saved_file)
print(password_saved)
However, password_saved = {url:password} resets the whole dictionary in to that one, so if you run it, it will just resets to only one, insead of saving all of it. So, I tried to replace it with:
password_saved[url] = password
But, then, it will say it is not defined. How can I define the dictionary without making any changes to it, including blank-spacing it?

Actually, your code is all fine. But, if you put in the same value 2 times, it won't show. Make sure to try different URLs for each one to make sure that everything works.

First, declare a dictionary then pass index and value to the dictionary.
password_saved = {}
password_saved[url] = password

when you say "it" is not defined, do you mean the dictionary? If so, this could just be a problem of initializing it before you call it. Right now, you are creating a new dictionary named "password_saved" with only one entry. It should look something like
password_saved = {}
...
password = str(input("What is your password that you want to save?"))
url = str(input("Which is the site that you want your password to save to?"))
password_saved[url] = password
with open('password_saved', 'wb') as password_saved_file:
pickle.dump(password_saved, password_saved_file)
print(password_saved)

Related

Convert text file to list then run functions on each list item in python?

Please bear with my this is my second week "coding". This is probably easy for you guys but it's really hard for me.
I'm stuck on an assignment for class. I need to save 5 passwords to a txt file, create a module to test if its a valid/strong password(8 characters, 1 upper, 1 lower, 1 special)
I have imported my function: password_check() but I cant figure out how to make it check each item in the list. I can do something like this:
pwd_file = open("passwords.txt", "r")
passwords = pwd_file.read()
print(passwords)
password_list = passwords.split(",")
from passval import password_check
password_check(password_list[0])
password_check(password_list[1])
password_check(password_list[2])
password_check(password_list[3])
password_check(password_list[4])
But it feels like cheating because I know how many items are in the list. Is there a better way to run a function on each list item?
You can use for loop. It iterates over the items of any sequence such as your password_list
for password in password_list:
password_check(password)
You can use for loop to validate/check it in dynamically
pwd_file = open("passwords.txt", "r")
passwords = pwd_file.read()
print(passwords)
password_list = passwords.split(",")
for password in password_list:
password_check(password)
I'd start with a good practice - using:
with open(file) as variable:
In your example variable would be pwd_file. It automaticly closes the file when you go back to your normal indentation. Apart from that, after using .split() method you have list of passwords, so you can iterate over them with for loop:
for password in list_name:
password_check(password)

Check if username already exists in database (Python + Pymongo)

I'm trying to make a registration module to use in a larger login/authentication program and I need to make a function that can check if a username already exists in a collection.
I haven't tried much more than this, this is my first real programming project and I'm stuck on this part. I realize I could use in-line dictionary databases, but I want to learn how to integrate 3rd party databases with my programming.
from pymongo import MongoClient
import time
client = MongoClient('localhost', 27017)
loginDB = client["loginDB"]
userCol = loginDB["userCol"]
##Username##
print('Choose A Unique Username')
time.sleep(1.2)
unameInput = input("Enter Username: ")
unameList = {'Username': unameInput}
unameQuery = {}
unameQuery2 = userCol.find_one({'Username.Username': {'$gt': 'a'}})
if unameInput != unameQuery2:
print('Name is Available | Accepted!')
allList = {'Username': unameList}
userCol.insert_one(allList)
else:
print('Sorry, Please Try Again.')`
The expected result is to search the database for everything that starts with the letter "a", forward. If the input (unameInput) does not equal anything in the query result (unameQuery2), then print "Username is available". If anything in the query matches the input, then print "Please try again", however, it's accepting everything that is input and exiting the code.
You are using find_one() to find one entry in Username and then checking if unameInput is equal to it. If it's not an exact match, it will execute the code for name is available.
Try find() instead as this will iterate over all the documents in the collection.
unameQuery2 = userCol.find()
if unameInput not in unameQuery2:
# do something
I figured it out, I was putting dictionaries inside of dictionaries inside of documents, as well as not iterating "allList".

Python giving list out of bounds but it shows both elements in the list [duplicate]

This question already has answers here:
How to read a file line-by-line into a list?
(28 answers)
Closed 7 months ago.
I'm trying to make a simple log in program using python (still fairly new to it), and I have the log in information stored in a text file for the user to match in order to successfully log in. Whenever I run it it says "list index out of range" but I'm able to print out the value of that element in the list, which is where I'm confused. I am trying to add the first line (username) and the second line (password) in the file to the list to compare to the user inputted values for each field, but am unable to compare them.
def main():
username = getUsername()
password = getPassword()
authenticateUser(username, password)
def getUsername():
username = input("Please enter your username: ")
return username
def getPassword():
password = input("Please enter your password: ")
return password
def authenticateUser(username, password):
credentials = []
with open("account_information.txt") as f:
content = f.read()
credentials.append(content)
if(username == credentials[0] and password == credentials[1]):
print("Login Successful!")
else:
print("Login Failed")
main()
You should use readline to get your infos in a list :
def authenticateUser(username, password):
credentials = []
with open("account_information.txt") as f:
content = f.readlines()
Using this, accordingly to what you describe, content[0] will be your username and content[1] your password.
Depending on what is in your account_information.txt, file.read might not be the function you want to use.
Indeed, read will return a string, that is a list of all the characters in the file. So if you have your username and password on two separate lines for instance
foo
H0weSomeP4ssworD
you may instead use readlines to parse your file into a list of strings where each element is a line within the file.
If you look at the python documentation at 7.2.1. Methods of File Objects, you'll see
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string or bytes object
You will see that f.read() is not the function you are looking for. try f.readlines() instead to put the content in a list of lines.
If you want to read all the lines of a file in a list you can also use list(f) or f.readlines().
After having "your problem solved", I invite you to come back to your problem description:
Python giving list out of bounds but it shows both elements in the list
What have you learned besides the fact that you have used the wrong method? I hope also something about your diagnostic skills. How should you print out a list to see how many items it contains?
If you do it like this
items = []
items.append("hello\nworld")
for i in items:
print(i)
you'll see:
hello
world
If you therefore deduce to have 2 items in the list, is this correct?
And python definitely reports that you're accessing the list out of bounds. You saw the conflict between your and python's perspective.
I think you should at least have learned using len() for out-of-bounds diagnostics today.

I cant get my simple shelve python script to work

Hey guys i am working on a project for school where i have to ask 10 math questions then store their score name and class but the only thing is i cant seem to get the right back to work in shelve. below is the code im trying to get to work any help would be good.
global username
global clss
global score
file = shelve.open('score.txt',writeback=True)
try:
file['score'] = (username, score, clss)
finally:
file.close ()
EDIT
The thing I am trying to do is to create a script that saves the score class and age of a person. the error im getting is that every time i run the script it deletes the previous data
EDIT change my code to
global username
global clss
global score
file = shelve.open('score',writeback=True)
try:
if 'scores' not in file.keys():
file['score'] = [ (username, score, clss) ]
else:
file['score'].append( (username, score, clss) )
finally:
file.close ()
As I mentioned above, writeback alone will not work if you are just using one tuple. If you want to append a list of user/score/class (i.e. subject) tuples, then do that. (Make sure to keep writeback set to true or else this direct call to append will not work).
try:
if 'scores' not in file.keys():
file['scores'] = [ (username, score, clss) ]
else:
file['scores'].append( (username, score, clss) )
Check the Python documentation for "open." https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
There is a second field, a string (e.g. "r+"), which changes whether the file is appended to, read-only, or re-written. That should help you.
You may want to bookmark the Python documentation online for more questions of this sort.

Python: How to store a REQUEST for input in a variable?

I'm building a text game and need to store 2 things in a single variable: a string, and a request for input. Note that I don't mean to store the output of the request - I mean that if the variable is called, both the string and the request itself are printed, after which the user answers the request.
raw_input("Do you do X or Y?") therefore doesn't work for me, because I need to store the request before I deploy it.
Some background about my approach:
Everything's stored in a dictionary, where the keys are the user's current location and the values are possible choices:
dict = {location1: (location2, location3), location2: (location1, location4)...}
So, I'll print location1, which will simultaneously print the string that describes that location, and make a request for input. The input triggers the program to print the next appropriate location, and the program keeps on going.
I'm trying to work out a recursive function that does this.
For each location, the request for input is worded differently, which is why I don't just build the request into my recursive function.
Sidenote: if anyone has any other suggestions/different approaches I should use instead, please share those too!
For each location, the request for input is worded differently,
Simply create another dictionary for input request corresponding to each location. For ex:
requests_dict = {
'location1': 'Please enter xxx: ',
'location2': 'Do you do X or Y: ', # and so on
}
Then use that dict to print the request.
user_input = raw_input(requests_dict['location2'])
Of course, you would like to make the last code based on some logic so that which one of that dicts is called, but I think you get the idea.
Update:
responses_dict = {}
user_input = raw_input(requests_dict['location2'])
responses_dict[user_input] = 'You are in %s' % user_input

Categories