简体   繁体   中英

How to group elements in a list of strings and convert them into a dictionary?

So my task is to convert a list of strings into a dictionary of tuples. keys and values for dictionary is separated by empty strings. For the dictionary, the key should be the student's name and the two values should be their mark and grade. Grade should be in string form.The list is like:

['John','85 A','90 A+','','David','71 B-','80 A-','','Liz','95 A+','66 C+']

This should give me a result of:

{'John':([85,90],['A','A+']),'David':([71,80],['B-','A-']),'Liz':([95,66],['A+','C+']}

I'm self learning tuple and dictionary so I don't know exactly how to separate strings into two parts corresponding to the key. Also get no idea on how to divide them into groups by '' empty string... Any help will be appreciated:)

Here is a new proposed solution.

list = ['John','85 A','90 A+','','David','71 B-','80 A-','','Liz','95 A+','66 C+']
newList = []
tmp = []
for element in list:
    if (element != ''):
        tmp.append(element)
    else:
        newList.append(tmp)
        tmp = []
newList.append(tmp)

students = {}
for student in newList:
    curStudent = student[0]
    students[curStudent] = ([], [])
    for i in range(1, len(student)):
        splitStr = student[i].split(" ")
        students[curStudent][0].append(int(splitStr[0]))
        students[curStudent][1].append(splitStr[1])

print(students)

First we are dividing the list by the space. We know the list will not end with a space, and so after iterating through the list, we append the tmp list to our newList. Our newList at the end will look something like this.

[['John', '85 A', '90 A+'], ['David', '71 B-', '80 A-'], ['Liz', '95 A+', '66 C+']]

Now we can iterate through each student easily. We know the first value will be the key, and any subsequent values will be a numeric and character grade. Since the first value is the key, we can create a tuple with 2 empty lists for the numeric and character grades. Since we are looping through a particular student, we know the first element is the key to the dictionary so we can append what we have parsed to that.

Our result is

{'John': ([85, 90], ['A', 'A+']), 'David': ([71, 80], ['B-', 'A-']), 'Liz': ([95, 66], ['A+', 'C+'])}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM