在python中将文本文件内容转换为字典的最有效方法 [英] most efficient way to convert text file contents into a dictionary in python
问题描述
以下代码实质上执行以下操作:
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:
文件:
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,请包括所有必要的信息供初学者使用
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
预先感谢
推荐答案
只需使用 csv
模块:
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()
是用于打开文件并处理关闭的上下文管理器.
with open()
is the same type of context manager you use to open the file, and handle the close.
csv.reader
是加载文件的方法,它返回一个可以直接迭代的对象,例如在理解列表中.但这不是使用理解列表,而是使用理解字典.
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)]
这篇关于在python中将文本文件内容转换为字典的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!