I’m new to python so apologies for the easy questions. I’m certainly missing something which is getting me confused.
This has something to do with nesting, splitting, and I’m guessing for loops but it’s not working out for me.
So here’s my original string:
name_scr = 'alvinone-90,80,70,50|simonthree-99,80,70,90|theotwo-90,90,90,65'
I’m trying to create a data structure – dict with the names and scores within it.
So this is what I started with:
test_scr = { }
new_name_scr = [list.split('-') for list in name_scr.split('|')]
# [['alvinone', '90,80,70,50'], ['simonthree', '99,80,70,90'], ['theotwo', '90,90,90,65']]
# this is not right, and since the output is a list of lists, I cannot split it again
I get stuck splitting this for the third time at the comma. So then I try the following:
test_scores = {}
for student_string in name_scr.split('|'):
for student in student_string.split('-'):
for scores in student.split(','):
test_scores[student] = [scores]
#but my result for test_scores (below) is wrong
#{'alvinone': ['alvinone'], '99,80,70,90': ['90'], 'theotwo': ['theotwo'], '90,80,70,50': ['50'], '90,90,90,65': ['65'], 'simonthree': ['simonthree']}
I want it to look like this:
{'alvinone': [99 80 70 50], 'simonthree': [90 80 70 90], 'theotwo': [90 90 90 65]}
So that when I do this:
print test_scores['simonthree'][2] #it's 70
Please help me here. Keep in mind I’m brand new to python so I don’t know too much just yet. Thank you.
Your split was correct, all you need to do is iterate over the values and convert it to dict, and to easily access the elements of the dict key, your value should be a list not a string…
Note: while splitting you have used variable name as ‘list’, which is not a good idea.
check this…