Model loc and iloc on a Series: one selects by label, the other by position.
What to build
A program that answers loc and iloc lookups on a Series.
Requirements
- The Series is given as
LABEL VALUElines. Each query isloc LABELoriloc POSITION. - Print the value, or
KeyError: 'LABEL'for an unknown label, orIndexError: single positional indexer is out-of-boundsfor a position outside -n to n - 1. As in Python and pandas, a negative position counts from the end: -1 is the last value.
Input
Line 1: n. Then n lines LABEL VALUE. Next line: q. Then q queries.
Output
q lines.
Constraints
1 ≤ n, q ≤ 100; labels are distinct words; values are whole numbers.
Example
Input:
3
apple 3
bread 2
milk 1
4
loc bread
iloc 0
loc tea
iloc 3
Output:
2
3
KeyError: 'tea'
IndexError: single positional indexer is out-of-bounds
Why it works
loc looks the label up in the index and iloc counts positions, from 0 at the start or from -1 at the end, which is why the same Series can answer both kinds of question.
Examples
Example 1 · Input
3 apple 3 bread 2 milk 1 4 loc bread iloc 0 loc tea iloc 3
Expected output
2 3 KeyError: 'tea' IndexError: single positional indexer is out-of-bounds
Example 2 · Input
2 x 10 y 20 2 iloc 1 loc x
Expected output
20 10
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Keep the labels and values in two lists, or in a dictionary plus a list of labels.
Hint 2
For iloc, a position p is valid when -n <= p < n, and Python's own list indexing then does the rest.
Solution
Show one correct solution (try it yourself first)
n = int(input())
labels = []
values = []
for _ in range(n):
label, value = input().split()
labels.append(label)
values.append(int(value))
q = int(input())
for _ in range(q):
kind, key = input().split()
if kind == "loc":
print(values[labels.index(key)] if key in labels else f"KeyError: '{key}'")
else:
p = int(key)
print(values[p] if -n <= p < n else "IndexError: single positional indexer is out-of-bounds")