I am trying to grab input and if the dictionary logins has a key that matches my input, I want to return the value of that key.
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
for logging in logins:
print(logins.values())
Try this.
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
value = logins.get(logging, "Not found")
print(value)
Thanks to #deceze for kind suggestion
If you need an iteration with for, try
for login in logins:
#do something with login
# e.g. if login == input
No looping necessary, just lookup by key.
logging = input('username: ')
value = logins.get(logging)
if value is not None:
print(value)
else:
print(f"username {logging!r} was not found")
Alternatively:
print(logins[logging])
however this will raise a KeyError exception if the key logging is not in the dictionary
You're on the right path. All you need to do is make use of the native property of dictionary to find if the element is in dictionary:
logins = {
'admin':'admin',
'turtle':'password123'
}
logging = input('username: ')
if logging in logins:
print(logins[logging])
Related
I am planning to use JSON file as a simple database, i am trying to append to it new entries and try to take my entries later.
This is the code i have:
import json
import time
try:
with open('json_database.json', 'r') as json_database:
profiles = json.load(json_database)
except FileNotFoundError:
profiles = []
while True:
answer = input('list info (l), write info (w), new info (a)').lower()
if answer == 'w':
break
elif answer == 'l':
print(profiles)
else:
username = input('username: ')
email = input('Email: ')
rating = input('Rating: ')
lichess_profiles.append({
'profile':{
'username': lichess_username,
'email': email,
'rating': rating
}
})
with open('json_database.json', 'w') as json_database:
json.dump(profiles, json_database)
Now i want to call the info from the JSON info ! thats what i added :
with open('json_database.json') as json_1:
result = json.load(json_1)
print(result['profile']['email'])
what is the reason of that ? what shall i add ?
i tried that code but it raise this error :
TypeError: list indices must be integers or slices, not str
The base item you are writing to the json file is a list, but you're treating it like a dictionary. It contains dictionaries, but you have to access it like a list:
print(result[0]['profile']['email'])
print(result[1]['profile']['email'])
# etc.
I am pulling from a dictionary in Python. I have it setup like this:
entries = [
{'website': 'yahoo','username': 'jblumberg','password': 'sdkljfhwe'},
{'website': 'google','username': 'jblumberg1','password': 'CoIushujSetu'}
]
I am asking the user to give me a website so I can return the password as so:
def lookup_password(website):
if website in entries.keys():
encrypted_password = entries[website]
return password_encrypt(encrypted_password, -encryption_key)
pass
However that won't give me what I want. How do I set it up to give me the password value for the provided website?
First let's restructure your dict like this so that it's a dict with each key as a website, like it seems you treat it in your code:
entries = {
'yahoo': {'username': 'jblumberg', 'password': 'sdkljfhwe'},
'google': {'username': 'jblumberg1', 'passwprd': 'CoIushujSetu'}
}
Now a couple of changes to your original code gets us to what should be working:
if website in entries:
encrypted_password = entries[website]['password']
I should note that website in entries and website in entries.keys() do the same thing here.
There are multiples small problems in your conception of your data :
First entries is a list. Therefore you won't be able to call ".keys()"
Also when using
encrypted_password = entries[website]
this will store the whole dictionnary. Meaning that you would then be able to access the password via ['password']
encrypted_password = entries[website]['password']
To resume : if you change you data to look like this
entries = {
'yahoo':{
'username': 'jblumberg','password': 'sdkljfhwe'
},
'google':{
'username': 'jblumberg1','password': 'CoIushujSetu'
},
}
def lookup_password(website):
if website in entries:
encrypted_password = entries[website]['password']
return password_encrypt(encrypted_password, -encryption_key)
pass
But if you keep the same data, it will have to look like this:
def lookup_password(website):
for record in entries:
if record['website'] == website:
encrypted_password = record['website']
return password_encrypt(encrypted_password, -encryption_key)
pass
You could use another dictionary:
entries = [
{'yahoo':{'username': 'jblumberg','password': 'sdkljfhwe'},
{'google':{'username': 'jblumberg1','password': 'CoIushujSetu'}
]
Then the following would happen:
>> website = 'yahoo'
>> entries[website]
>> {'username': 'jblumberg','password': 'sdkljfhwe'}
so if you wanted the password:
>> entires[website]['password']
>> 'sdkljfhwe'
Try:
def lookup_password(website):
for entry in entries:
if entry['website'] == website:
return entry['password']
Output:
In[2]: lookup_password('google')
Out[2]: 'CoIushujSetu'
I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!
Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )
Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".
I am trying to check if I have an entry in my database using this code:
def device_update(request):
json_data = json.loads(request.body)
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
However, when the code reaches the if statement to check if the group exists, it returns error 500.
I tried to check with two groups one that exists and another one that doesn't, in both cases I got error 500.
How can I fix this and why is this happening?
The logic for checking if a Group exists, i.e. the line:
if Group.objects.filter(group=group_name).exists()
is not throwing the error here. It is likely that json_data is missing one of the keys you expect it to have, for example, 'group'.
I'd recommend using the get method that dictionaries have. This provides default values when the specified key is not present in the dictionary. You should also have error handling for when the request body is not in valid JSON format.
Here's an example:
def device_update(request):
try:
json_data = json.loads(request.body)
except json.JSONDecodeError:
return HttpResponse('Request body must be in valid JSON format')
email = json_data.get('email', '')
imei = json_data.get('imei', '')
sdk_version = json_data.get('sdk_version', '')
date = json_data.get('updateDate', '')
rule = json_data.get('ruleName', '')
group_name = json_data.get('group', '')
if Group.objects.filter(group=group_name).exists():
print("group does exists")
else:
print("group doesn't exists")
return HttpResponse("Successful")
I set the defaults to the empty string '', but you may want to change that.
Your view doesn't have any error handling. Looking at it quickly, at least two things could go wrong. The request body might not be valid json, and if it is valid json, it might not contain the required keys.
def device_update(request):
try:
json_data = json.loads(request.body)
except ValueError:
return HttpResponse("Invalid json")
try:
email = json_data['email']
imei = json_data['imei']
sdk_version = json_data['sdk_version']
date = json_data['updateDate']
rule = json_data['ruleName']
group_name = json_data['group']
except KeyError as e:
return HttpResponse("Missing Key %s" % e[0])
...
Writing your own validation for a single view like this is ok. As it gets more complicated, you might want to look at django rest framework. It has serializers which will help you manage validation.
Alasdair/Keselme, looks that your view is correct.
Try to put the ipdb into your code in order to debug your code, and than you can print the request.data and see what is comming in the request.
I am making a webserver+website with python and I am currently figuring out how to check if your login values are correct. Previously for testing I used the following code:
def checkUser(username, password): #<-- input values go in here
site_usernames = ["admin", "username1", "username2"]
site_passwords = ["admin", "password1", "password2"]
site_couples = {"admin":"admin", "username1":"password1", "username2":"password2"}
not_counter = 0
while True:
if username in site_usernames:
if password in site_passwords:
for key in site_couples:
if (username == key) and (password == site_couples[key]):
print("User %s logged in!" % username)
return True
else:
not_counter = not_counter + 1
if not_counter > 10:
print("User failed login with accountname: %s" % username)
return False
break
else:
continue
else:
pass_exists = False
break
else:
user_exists = False
break
As far as I have seen, You can not return two columns from a database as a dictionary. I have managed to get one column as a list, and I am planning to use that.
So in my new code, I have the following:
A list of usernames that are in the database
A list of encoded passwords in the database
I would like to make an authentication function that checks if:
If the username exists in the database:
If the password exists in the database:
If the input username:password couple exists in all existing username:password values in the database:
return True if all checks succeed
The problem is that I find it very difficult to manage such a thing. As you can see in my example code, I had two lists and a dict, all pre-defined. I would like to create those things on the fly, and the only one I actually need help with is how to create the username:password dictionary couples. How would I do such a thing? zip() makes tuples and not dictionaries.
In [1]: users = ["user1", "user2"]
In [2]: pws = ["password", "12354"]
In [3]: dict(zip(users, pws))
Out[3]: {'user1': 'password', 'user2': '12354'}