The following code essentially does the following:
My question is: is there an easier more efficient (quicker) method of creating the dictionary from the file contents:
File:
user1,pass1
user2,pass2
Code
def login():
print("====Login====")
usernames = []
passwords = []
with open("userinfo.txt", "r") as f:
for line in f:
fields = line.strip().split(",")
usernames.append(fields[0]) # read all the usernames into list usernames
passwords.append(fields[1]) # read all the passwords into passwords list
# Use a zip command to zip together the usernames and passwords to create a dict
userinfo = zip(usernames, passwords) # this is a variable that contains the dictionary in the 2-tuple list form
userinfo_dict = dict(userinfo)
print(userinfo_dict)
username = input("Enter username:")
password = input("Enter password:")
if username in userinfo_dict.keys() and userinfo_dict[username] == password:
loggedin()
else:
print("Access Denied")
main()
For your answers, please:
a) Use the existing function and code to adapt b) provide explanations /comments (especially for the use of split/strip) c) If with json/pickle, include all the necessary information for a beginner to access
Thanks in advance
Just by using the csv
module :
import csv
with open("userinfo.txt") as file:
list_id = csv.reader(file)
userinfo_dict = {key:passw for key, passw in list_id}
print(userinfo_dict)
>>>{'user1': 'pass1', 'user2': 'pass2'}
with open()
is the same type of context manager you use to open the file, and handle the close.
csv.reader
is the method that loads the file, it returns an object you can iterate directly, like in a comprehension list. But instead of using a comprehension list, this use a comprehension dict.
To build a dictionary with a comprehension style, you can use this syntax :
new_dict = {key:value for key, value in list_values}
# where list_values is a sequence of couple of values, like tuples:
# [(a,b), (a1, b1), (a2,b2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With