在python中将文本文件内容转换为字典的最有效方法

Mis*_*ing 3 python dictionary file

以下代码基本上执行以下操作:

  1. 获取文件内容并将其读入两个列表(剥离和拆分)
  2. 将两个列表一起压缩成字典
  3. 使用字典创建"登录"功能.

我的问题是:是否有更简单,更有效(更快)的方法从文件内容创建字典:

文件:

user1,pass1
user2,pass2
Run Code Online (Sandbox Code Playgroud)

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()
Run Code Online (Sandbox Code Playgroud)

为了您的答案,请:

a)使用现有的函数和代码进行调整b)提供解释/注释(特别是使用split/strip)c)如果使用json/pickle,请包含初学者访问的所有必要信息

提前致谢

PRM*_*reu 8

只需使用该csv模块:

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'}
Run Code Online (Sandbox Code Playgroud)

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)]
Run Code Online (Sandbox Code Playgroud)