Barry
Barry

Reputation: 1

Converting the value in a text into a dictionary

I have a text file that looks like this.

Paul Velma 63.00
Mcgee Kibo 71.00
Underwood Louis 62.75
Clemons Phyllis 57.50

I am trying to make them into a dictionary but I got stuck because I am not sure how to slice them into keys and values. Below is my code.

dt_stu=[]
infile = open("C:\\Users\kwokw\Downloads\\student_avg.txt",'r')
for line in infile:
    key,value=line.split([0:9])
    dt_stu[key]=value
print(dt_stu)

Upvotes: 0

Views: 71

Answers (3)

omar hafez
omar hafez

Reputation: 11

str.rsplit() lets you specify how many times to split

s = "a,b,c,d"
s.rsplit(',', 1)

Output: ['a,b,c', 'd']

I edited your code try this:

dt_stu={}
infile = open("draft.txt",'r')
for line in infile:
    key,value = line.rsplit(' ', 1)
    dt_stu[key]=float(value.strip())
print(dt_stu)

Output: {'Paul Velma': 63.0, 'Mcgee Kibo': 71.0, 'Underwood Louis': 62.75, 'Clemons Phyllis': 57.5}

Upvotes: 1

Алексей Р
Алексей Р

Reputation: 7627

You can use rsplit() with maxsplit=1 for convenient line splitting

dt_stu={}
for line in infile:
    key, value = line.rsplit(maxsplit=1)
    dt_stu[key] = value
{'Paul Velma': '63.00', 'Mcgee Kibo': '71.00', 'Underwood Louis': '62.75', 'Clemons Phyllis': '57.50'}

Upvotes: 1

thomaskeefe
thomaskeefe

Reputation: 2404

Use the .split method of strings to split on the spacebar, i.e. my_string.split(" "). Then iterate through that list.

Upvotes: 0

Related Questions