Nested Dictionary Path
Python
Hard
3 views
Problem Description
You will receive q commands on a nested dictionary: SET path value, GET path. Path is dot separated like a.b.c. For GET output value if exists else NOT FOUND.
Input Format
First line q. Next q lines commands.
Output Format
Outputs for GET.
Sample Test Case
Input:
6
SET user.name Ravi
SET user.age 20
GET user.name
GET user.city
SET user.city Delhi
GET user.city
Output:
Ravi
NOT FOUND
Delhi
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if not lines: sys.exit(0)
q=int(lines[0].strip())
root={}
out=[]
for i in range(1,1+q):
parts=(lines[i] if i<len(lines) else '').split()
if len(parts)<2: continue
cmd=parts[0]
path=parts[1]
keys=path.split('.')
if cmd=='SET':
val=parts[2] if len(parts)>=3 else ''
cur=root
for k in keys[:-1]:
nxt=cur.get(k)
if not isinstance(nxt,dict):
nxt={}
cur[k]=nxt
cur=nxt
cur[keys[-1]]=val
else:
cur=root
ok=True
for k in keys:
if isinstance(cur,dict) and k in cur:
cur=cur[k]
else:
ok=False
break
out.append(str(cur) if ok and not isinstance(cur,dict) else 'NOT FOUND')
sys.stdout.write('\
'.join(out))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!