1

If you are given a .txt file which contains these contents:

James Doe 2/16/96 IT210 A BUS222 B PHY100 C
John Gates 4/17/95 IT101 C MATH112 B CHEM123 A
Butch Thomas 1/28/95 CS100 C MATH115 C CHEM123 B

How can you get it so it takes the class names and grades and puts them into an empty dictionary while ignoring the rest? I have code set up to read the .txt file but got stuck. Any suggestions?

This is my code for opening the file:

def readFile():
    new_dict = {}
    myFile = open('Students.txt', 'r')
    for line in myFile:
6
  • Can you give us an example of what the Dictionary would look like in this case? Commented Jul 18, 2013 at 4:34
  • And what are the class names and grades in that file? Commented Jul 18, 2013 at 4:34
  • Dict = {'IT210': 'A', 'BUS222': 'B', 'PHY100': 'C'} Commented Jul 18, 2013 at 4:38
  • something like that for the first line Commented Jul 18, 2013 at 4:38
  • Are the two spaces between the date and the first course intentional? Commented Jul 18, 2013 at 4:42

6 Answers 6

2

Instead of making different variables for each student, why not use a list of dictionaries?

See the code below :

>>> dictList = []
>>> with open('Students.txt', 'r') as f:
        for line in f:
            elements = line.rstrip().split(" ")[3:]
            dictList.append(dict(zip(elements[::2], elements[1::2])))       
>>> dictList
[{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]

If you're looking to maintain the order as given in the txt file in the dictionary, then look into an OrderedDict.

Sign up to request clarification or add additional context in comments.

Comments

1

Anser:

def readFile():
    new_dict = {}
    myFile = open('Students.txt', 'r')
    for line in myFile:
        line2=line.split()
        class1=line2[3]
        gra=line2[4]
        new_dict[class1]=gra

Comments

0
li = []
with open("file.txt", 'r') as f:
    line = f.readline().split()
    while line:
        dict = {}
        dict[line[-6]] = line[-5]
        dict[line[-4]] = line[-3]
        dict[line[-2]] = line[-1]
        li.append(dict)
        line = f.readline().split()

li = [{'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}, {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}]

Comments

0

The below code does what you want.

import re

student = 'James Doe 2/16/96  IT210 A BUS222 B PHY100 C'
pattern = '([0-9]{1,2}/[0-9]{1,2}/[0-9]{1,2})'
end = re.search(pattern, student).end()
found = student[end+2:]
x = found.split(' ')
numberOfEntries = len(x) / 2
i = 0
Dict = {}

while i < numberOfEntries:
    Dict[x[i]] = x[i+1]
    i = i + 1

print Dict

Comments

0
dic={}
for line in myFile:
   info=line.split(' ')
   firstname=info[0]
   lastname=info[1]
   firstClass=info[3]
   firstgrade=info[4]
   secondClass=info[5]
   secondgrade=info[6]
   thirdClass=info[7]
   thirdGrade=info[8]
   gradeInfo={firstClass:firstgrade,secondClass:secondgrade,thirdClass:thirdgrade}
   name='%s %s' %(firstname,lastname)
   dic+={name,gradeInfo}

Comments

0
student_dict = {}
for line in open('input','r'):
    line2=line.split()
    name = ' '.join(line2[0:2])
    grades = line2[3:]
    grades_dict = {grades[i]:grades[i+1] for i in xrange(0,len(grades),2)}
    student_dict[name]=grades_dict

gives:

>>> student_dict
{'James Doe': {'IT210': 'A', 'PHY100': 'C', 'BUS222': 'B'}, 'Butch Thomas': {'CS100': 'C', 'CHEM123': 'B', 'MATH115': 'C'}, 'John Gates': {'IT101': 'C', 'MATH112': 'B', 'CHEM123': 'A'}}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.