Last Value for Key
Python
Easy
5 views
Problem Description
Read n pairs key value. If a key appears many times, keep the last value. After all pairs, output value for query key, or NA if key never appeared.
Input Format
First line n. Next n lines: key value. Last line: queryKey.
Output Format
One line value or NA.
Sample Test Case
Input:
4
a 10
b 5
a 7
c 2
a
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
n=int(lines[0].strip())
d={}
for i in range(1,1+n):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
d[parts[0]]=parts[1]
q=(lines[1+n] if 1+n<len(lines) else '').strip()
sys.stdout.write(d.get(q,'NA'))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!