user5272899
user5272899

Reputation:

Defining a dictionary in Python 3

I have the following code and want to turn a string from a file into a dictionary (to be read in and manipulated). In the following code, on execution, it comes up with an error: 'people is not defined'. Have I not defined this correctly or is the syntax wrong? This is Python 3

def verifylogin():
people={}
with open("moosebook.txt","r") as f:
for line in f:
    items=line.split(",")
    person={}
    person['username'] =items[0]
    person['password']=items[1]
    person['Gender']=items[2]
    person['Career']=items[3]
    people[items[0]]=person

    print(person[0])

Upvotes: 0

Views: 327

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

I am not sure what your end intention for your script is, but the following might be helpful. Python has a built in CSV module that can automatically read each line of your file in as a list of columns.

Furthermore, it has a CSV DictReader variation which might be more useful to you. This takes the first row in your CSV file and uses the header to automatically create a dictionary for each row as it is read in.

If your file does not contain a header row, a list of suitable fieldnames can be provided. By using this feature, you do not need to create your dictionary.

The following shows you how you could create a people dictionary. The key being the username for each of your rows. I remove the username key from person as it then becomes the key used by people:

import csv

def verifylogin():
    people = {}

    with open("moosebook.txt","r") as f:
        for person in csv.DictReader(f):
            print("Person: ", person)
            username = person['username']
            del person['username']
            people[username] = person

    print("People:", people)
    print("Wilma's career:", people['Wilma']['Career'])     

verifylogin()

So, if moosebook.txt contained the following entries:

username,password,Gender,Career
Fred,Password1,Male,Builder
Wilma,Password2,Female,Teacher

You would see the following output:

Person:  {'Career': 'Builder', 'password': 'Password1', 'username': 'Fred', 'Gender': 'Male'}
Person:  {'Career': 'Teacher', 'password': 'Password2', 'username': 'Wilma', 'Gender': 'Female'}
People: {'Wilma': {'Career': 'Teacher', 'password': 'Password2', 'Gender': 'Female'}, 'Fred': {'Career': 'Builder', 'password': 'Password1', 'Gender': 'Male'}}
Wilma's career: Teacher

If your file does not have a header row, the following line could be changed:

csv_input = csv.DictReader(f, fieldnames=['username', 'password', 'Gender', 'Career'])

Upvotes: 1

HelloWorld
HelloWorld

Reputation: 1863

As you can see from the comments the indention is wrong, but I guess this comes from the paste here on SO and is not the issue in your actual code.

But you two other issues in your code. print(person[0]) will fail when executed because 0 is not a valid key for your dictionary here. The only valid keys in your code are username, password, Gender and Career. Therefore you can use person or people[items[0]]. Then you could use splitlines to avoid newlines in your data.

def verifylogin():
    people = {}
    with open("moosebook.txt", "r") as f:
        for line in f.read().splitlines():  # Fixed line
            items = line.split(",")
            person = {}
            person['username'] = items[0]
            person['password'] = items[1]
            person['Gender'] = items[2]
            person['Career'] = items[3]
            people[items[0]] = person
            print(people[items[0]])  # Fixed line

Upvotes: 1

Related Questions