【问题标题】:most efficient way to convert text file contents into a dictionary in python在python中将文本文件内容转换为字典的最有效方法
【发布时间】:2018-02-14 04:55:32
【问题描述】:

下面的代码基本上做了以下事情:

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

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

文件:

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) 提供解释/cmets(特别是对于split/strip的使用) c) 如果使用 json/pickle,请包括初学者访问的所有必要信息

提前致谢

【问题讨论】:

标签: python file dictionary


【解决方案1】:

只需使用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)]

【讨论】:

  • 能否请您解释一下,对于初学者和教学目的,key:passw 用于关键部分。我想那里可以使用任何变量吗?你也可以评论说它到底在做什么(我的意思不是那一行)
  • MissComputing 感谢您的反馈,记住@endo.anaconda 的评论,下一步是用一些哈希替换密码
【解决方案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

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 2020-09-24
    • 2022-06-15
    • 2020-12-16
    • 2023-03-15
    • 2015-02-08
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多