Please be gentle, I’m very new to programming and only own one book which is giving me some terrible directions (Head First Programming). Here is the code I have in the Python IDLE:
scores = {}
scores[8.45] = 'Zach'
scores[9.12] = 'Juan'
scores[8.31] = 'Aaron'
scores[8.05] = 'Aideen'
scores[8.65] = 'Johnny'
scores[7.81] = 'Stacey'
for key in scores.keys():
print(scores[key] + ' had a score of ' + scores[???])
The program is meant to print a list containing both the names of the contestants and their corresponding scores but I dont know what I am doing wrong or right at this point :/
EDIT: Thank you guys. With your help i edited the code to working order, if you’re interested here it is:
scores = {}
scores['Zach'] = 8.45
scores['Juan'] = 9.12
scores['Aaron'] = 8.31
scores['Aideen'] = 8.05
scores['Johnny'] = 8.65
scores['Stacey'] = 7.81
for key in scores.keys():
print(str(key), ' had a score of ' , scores[key])
You can use the
{...}.items()iterator as follows:However, your dictionary is in the wrong order. For example, what if Zach and Juan had the same score of 9.10? Then, writing
scores[9.10]='Zach' scores[9.10]='Juan'would overwrite Zach! The keys should be the names.You can write it like this:
For the record, here’s how I’d do it from scratch: