6. What are the names of the winners?¶

6.1. Using another list¶
We can use two lists to find out.
The
names
andscores
lists to save the names and scores obtained by the participants respectively.
surf4_en.txt
file = open("surf4_en.txt")
scores = []
names = []
for line in file:
name, points = line.split()
scores.append(float(points))
names.append(name)
file.close()
scores.sort(reverse=True)
names.sort(reverse=True)
print(f"1. {names[0]} {scores[0]:.2f}")
print(f"2. {names[1]} {scores[1]:.2f}")
print(f"3. {names[2]} {scores[2]:.2f}")
Activity: 6.1.2 ActiveCode (ac_l37_6a_en)
6.2. But these data are incorrect!¶
There must be a problem because Zack is really bad!
What happened?
By sorting the
names
list in decreasing order, the character'Z'
ends up being the first.The correspondence between scores and the names of the participants is lost.
Another data structure is needed to avoid losing the correspondence.
6.3. We need to join the lists¶

6.4. Using and sorting a dictionary¶
Using a dictionary and seeing all its elements iteratively.
Print output (drag lower right corner to resize)
|
Activity: CodeLens 6.4.1 (cl_l37_6_en)
Using a dictionary for the championship.
file = open("surf4_en.txt")
scores = {}
for line in file:
name, points = line.split()
scores[float(points)] = name
file.close()
for participant in sorted(scores, reverse=True):
print(f"{scores[participant]} obtained a score of {participant:.2f}")
Activity: 6.4.2 ActiveCode (ac_l37_6b_en)
Activity: 6.4.3 Poll (TWP37E)