Problem overview
The method toDictionary receives a list of strings, names, and a list of integers, scores, of the same length. It returns a dictionary in which each name is a key and the score at the same index is its value.
For names = ["Ana", "Ben", "Cara"] and scores = [90, 75, 88] the result is {'Ana': 90, 'Ben': 75, 'Cara': 88}. The score at index 0 belongs to the name at index 0, and so on. The names are all different, but two names can share a score: ["Zoe", "Adam"] with [60, 60] gives {'Zoe': 60, 'Adam': 60}, two separate entries. Two empty lists give the empty dictionary {}.
Approach: one index reaches both lists
The two lists are linked only by position. A name and its score sit at the same index, so a loop over the indices can read both with the same number. For each index i, names[i] becomes a key and scores[i] its value.
Dictionaries create entries on assignment. Writing result[key] = value adds the key when it isn't there and replaces its value when it is. Since the names are all different, every assignment adds a new entry.
A different way to think about the loop: it walks along both lists at once, with the index as the shared pointer. At i = 0 it reads "Ana" and 90, at i = 1 it reads "Ben" and 75, and so on until the names run out.
Step by step
- Create an empty dictionary named
result. It gets one entry per name. - Loop over the indices with
for i in range(len(names)).len(names)is the number of names, andrangeof it produces the indices from 0 up to one less. - Store the pair:
result[names[i]] = scores[i]. - Return
resultafter the loop.
The solution in Python
class Solution:
def toDictionary(self, names: List[str], scores: List[int]) -> Dict[str, int]:
result = {}
for i in range(len(names)):
result[names[i]] = scores[i]
return result
Notes on the code:
- The key is on the left of the
=. Inresult[names[i]] = scores[i], the expression inside the brackets is the key, and the right side is the value. - Empty input works without a special case. With empty lists,
range(0)has no indices, the loop body never runs, and the function returns the empty dictionary. - Duplicate keys overwrite. Names are all different in this lesson, but if a name appeared twice, the later score would replace the earlier one.
["Ana", "Ana"]with[1, 2]would give{'Ana': 2}, with one entry instead of two. - A built-in shortcut.
dict(zip(names, scores))pairs the two lists and builds the same dictionary in one line. The index loop shows whatzipdoes.
Edge cases and common mistakes
- Looping over the wrong thing.
for i in namesgives names, not numbers, andscores[i]would then fail. Userange(len(names))when you need the position. - Swapping key and value.
result[scores[i]] = names[i]makes the scores the keys, and equal scores would overwrite each other. With["Zoe", "Adam"]and[60, 60], only one entry would survive. - Off-by-one ranges.
range(len(names) - 1)skips the last name.range(len(names) + 1)runs past the end and raises anIndexError. - Lists of different lengths. The lesson guarantees the same length. With a shorter
scores, the loop would raiseIndexErrorat the first missing score. - One entry.
["Max"]with[100]gives{'Max': 100}.
Testing
["Ana", "Ben", "Cara"]and[90, 75, 88]give{'Ana': 90, 'Ben': 75, 'Cara': 88}.["Zoe", "Adam"]and[60, 60]give{'Zoe': 60, 'Adam': 60}.[]and[]give{}.["Max"]and[100]give{'Max': 100}.
