Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The following code essentially does the following:

  1. Takes file contents and reads it into two lists (stripping and splitting)
  2. Zips the two lists together into a dictionary
  3. Uses the dictionary to create a "login" feature.

My question is: is there an easier more efficient (quicker) method of creating the dictionary from the file contents:

File:

user1,pass1
user2,pass2

Code

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()

For your answers, please:

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

Thanks in advance

like image 649
Compoot Avatar asked Sep 13 '25 02:09

Compoot


1 Answers

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() is the same type of context manager you use to open the file, and handle the close.

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)]
like image 66
PRMoureu Avatar answered Sep 14 '25 16:09

PRMoureu