以下代码基本上执行以下操作:
我的问题是:是否有更简单,更有效(更快)的方法从文件内容创建字典:
文件:
user1,pass1
user2,pass2
代码
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()
请回答:
a)使用现有的功能和代码进行调整 b)提供解释/评论(特别是对分裂/条带的使用) c)如果使用json / pickle,请包含初学者访问的所有必要信息
提前致谢
答案 0 :(得分:8)
只需使用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()
与用于打开文件和处理关闭的上下文管理器类型相同。
csv.reader
是加载文件的方法,它返回一个可以直接迭代的对象,就像在理解列表中一样。但不是使用理解列表,而是使用理解词典。
要构建具有理解风格的字典,可以使用以下语法:
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)]
答案 1 :(得分:2)
如果您不想使用csv
模块,您可以执行以下操作:
userinfo_dict = dict() # prepare dictionary
with open("userinfo.txt","r") as f:
for line in f: # for each line in your file
(key, val) = line.strip().split(',')
userinfo_dict[key] = val
# now userinfo_dict is ready to be used