Nested Dictionary Path

Nested Dictionary Path

Hard Python Dictionaries 9 views
Explanation Complexity

Problem Statement

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.

Example

6
SET user.name Ravi
SET user.age 20
GET user.name
GET user.city
SET user.city Delhi
GET user.city
Ravi
NOT FOUND
Delhi

Constraints

1

Input / Output Format

Input Format
First line q. Next q lines commands.
Output Format
Outputs for GET.
Constraints
1

Examples

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

Example Solution (Public)

Python
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))

Official Solution Code

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))
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.