Start learning free

LESSON 227 OF 673 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Two Lists to a Dictionary in Python: Pairing by Index

Practice Read the full explanation

Given a list of strings names and a list of integers scores of the same length, pair each name with the score at the same index. Return a dict where names[i] is a key and scores[i] is its value.

The names are all different, while two names can have the same score. If names and scores are empty, return an empty dict. The order of the entries doesn't matter.

Example 1:

Input: names = ["Ana", "Ben", "Cara"], scores = [90, 75, 88]
Output: {"Ana": 90, "Ben": 75, "Cara": 88}
Explanation: "Ana" is at index 0 in names, and the score at index 0 is 90. The same goes for "Ben" with 75 and "Cara" with 88.

Example 2:

Input: names = ["Zoe", "Adam"], scores = [60, 60]
Output: {"Zoe": 60, "Adam": 60}
Explanation: Two names with the same score are two different entries.

Example 3:

Input: names = ["Max"], scores = [100]
Output: {"Max": 100}
Explanation: One name gives a single entry.
STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Two Lists To A Dictionary in Python, explained

    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

    1. Create an empty dictionary named result. It gets one entry per name.
    2. Loop over the indices with for i in range(len(names)). len(names) is the number of names, and range of it produces the indices from 0 up to one less.
    3. Store the pair: result[names[i]] = scores[i].
    4. Return result after 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 =. In result[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 what zip does.

    Edge cases and common mistakes

    • Looping over the wrong thing. for i in names gives names, not numbers, and scores[i] would then fail. Use range(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 an IndexError.
    • Lists of different lengths. The lesson guarantees the same length. With a shorter scores, the loop would raise IndexError at 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}.
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free