在python中将文本文件内容转换为字典的最有效方法
以下代码基本上执行以下操作:在python中将文本文件内容转换为字典的最有效方法,python,file,dictionary,Python,File,Dictionary,以下代码基本上执行以下操作: 获取文件内容并将其读入两个列表(剥离和拆分) 将这两个列表合并到一本词典中 使用字典创建“登录”功能 我的问题是:是否有一种更简单、更有效(更快)的方法可以从文件内容创建字典: 文件: user1,pass1 user2,pass2 代码 def login(): print("====Login====") usernames = [] passwords = [] with open("userinfo.txt", "r")
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,请包含初学者可以访问的所有必要信息
只需使用以下工具,即可提前感谢您:
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)]
如果您不想使用
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
永远不要将密码保存在明文中,你应该使用某种散列函数,例如,对于初学者和教学目的,你能解释一下密钥部分的密钥:passw吗。我想在那里可以使用任何变量吗?另外,你能评论一下它到底在做什么吗(不,我指的是那一行)计算错误谢谢你的反馈,记住@endo.anaconda的评论,下一步是用一些散列替换密码
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