S1Q3 · Make Dictionary from Elements in Index of Lists¶
⚡ Quick Reference
Function: make_dict_from_elems_in_index(keys, values, index: int) -> dict
Core idea: index both lists at the same position, return a single-pair dictionary.
def make_dict_from_elems_in_index(keys, values, index: int) -> dict:
return {keys[index]: values[index]}
Key rules:
- Returns a dict with exactly one key-value pair
- index can be negative (Python supports negative indexing)
- Index is always within valid bounds - no need for a guard
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] - The value is
values[index]
Examples:
keys = ['apple', 'banana', 'cherry']
values = [10, 20, 30, 40]
index = 1
{'banana': 20}
keys = ['apple', 'banana', 'cherry']
values = [10, 20, 30, 40]
index = -1
{'cherry': 40}
Understanding the problem¶
The function simply picks one element from each list at the same index position and wraps them in a dictionary:
keys = ['apple', 'banana', 'cherry']
↑
values = [10, 20, 30, 40]
↑
index = 1 → key = 'banana', value = 20
Result → {'banana': 20}
For index = -1 (last element):
Negative indexing
Python supports negative indices - -1 means the last element, -2 means second from last, and so on. keys[-1] = 'cherry', values[-1] = 40. No special handling needed; Python does it natively.
Tracing the examples¶
Example 1: index = 1
| List | list[1] |
|---|---|
keys |
'banana' |
values |
20 |
Result: {'banana': 20}
Example 2: index = -1
| List | list[-1] |
|---|---|
keys |
'cherry' (last element) |
values |
40 (last element) |
Result: {'cherry': 40}
Note that keys has 3 elements and values has 4 - they don't need to be the same length. The function just indexes each independently.
Solution approaches¶
def make_dict_from_elems_in_index(keys, values, index: int) -> dict:
return {keys[index]: values[index]}
A single-pair dict literal. Clean, direct, and the most Pythonic form.
Key takeaways¶
Single-pair dict literal
{k: v} creates a dictionary with one key-value pair. No need for dict() or any loop when you already have the key and value.
Negative indexing works everywhere
Python's negative indices work on any sequence - lists, strings, tuples. lst[-1] is the last element, lst[-2] is second from last. No length calculation needed.
Lists don't need to be the same length
The two lists are indexed independently - they can have different lengths. The problem guarantees the index is valid for both, so no bounds checking is needed.