S1Q3 · Make Dictionary from Elements at Index¶
⚡ Quick Reference
Function: make_dict_from_elems_in_index(keys, values, index) -> dict
Core idea: Index both lists at the same position, wrap in a dict literal.
Key rules: - Returns a dict with exactly one key-value pair - Index is applied independently to both lists (they can have different lengths) - Negative indices work as normal Python indexing
Problem Statement¶
Problem
Write a function make_dict_from_elems_in_index(keys, values, index) that returns a dictionary with a single key-value pair, where the key is keys[index] and the value is values[index]. The index is always valid for both lists.
Examples:
keys = ['apple', 'banana', 'cherry']
values = [10, 20, 30, 40]
make_dict_from_elems_in_index(keys, values, 1)
{'banana': 20}
make_dict_from_elems_in_index(keys, values, -1)
{'cherry': 40}
Understanding the problem¶
The two lists are indexed independently at the same position:
| Index | keys |
values |
Result |
|---|---|---|---|
0 |
'apple' |
10 |
{'apple': 10} |
1 |
'banana' |
20 |
{'banana': 20} |
2 |
'cherry' |
30 |
{'cherry': 30} |
-1 |
'cherry' |
40 |
{'cherry': 40} |
Lists can have different lengths
Notice that keys has 3 elements and values has 4. The index is applied to each list separately, so values[-1] gives 40 (last of 4) while keys[-1] gives 'cherry' (last of 3). This is by design -- the problem guarantees the index is valid for both.
Solution approaches¶
Key takeaways¶
Single-pair dict literal: {k: v}
The simplest way to create a one-item dictionary is the literal {key: value}. No need for dict() or .update() when you already have the key and value in hand.
Negative indexing
Python supports negative indices: -1 is the last element, -2 is second-to-last, and so on. They work identically on any list regardless of its length.
Independent indexing on two lists
The two lists don't need to be the same length -- the same index just resolves independently for each. keys[index] and values[index] are two separate lookups that happen to use the same integer.