ProgrammingVery hardGATE CS · Product-company placement

What is printed?

What is printed?
def walk(d, depth=0):
    out = []
    for k, v in d.items():
        out.append(f"{k}{depth}")
        if isinstance(v, dict):
            out += walk(v, depth + 1)
    return out
print(walk({"a": {"b": {}, "c": {"d": 1}}, "e": 2}))
  1. A. ['a0', 'b1', 'c1', 'd2', 'e0']
  2. B. ['a0', 'e0', 'b1', 'c1', 'd2']
  3. C. ['a0', 'b1', 'c1', 'e0']
  4. D. ['a0', 'b1', 'c1', 'd2', 'e1']

Correct answer: A. ['a0', 'b1', 'c1', 'd2', 'e0']

The recursion is depth-first and preserves dict insertion order. 'b' maps to an empty dict, which is still a dict, so recursion happens but adds nothing; 'd' maps to 1, so it is listed but not recursed.

More Python Programming questions

Exams that ask this topic