Home > Back-end >  Converting the value in a text into a dictionary
Converting the value in a text into a dictionary

Time:11-14

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)

CodePudding user response:

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'}

CodePudding user response:

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}

CodePudding user response:

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

CodePudding user response:

Value is the last element of your splitted list. You can get the key by joining all but the last element again:

dt_stu=dict()
infile = open("C:\\Users\kwokw\Downloads\\student_avg.txt",'r')
for line in infile:
    words = line.split()
    key = " ".join(words[:-1])
    value = words[-1]
    dt_stu[key]=value
print(dt_stu)
  • Related