簡體   English   中英

在python中將文本文件內容轉換為字典的最有效方法

[英]most efficient way to convert text file contents into a dictionary in python

以下代碼基本上執行以下操作:

  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)提供解釋/注釋(特別是使用split / strip)c)如果使用json / pickle,請包含初學者訪問的所有必要信息

提前致謝

只需使用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'}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM