ProgrammingVery hardProduct company OA

What is printed?

What is printed?
d = {"b": 1, "a": 2, "c": 3}
d["a"] = 9
d.update(b=7, d=4)
d["c"] = d.pop("c")
d.setdefault("a", 0)
e = {**d, "b": 0}
print(list(d), list(e), next(reversed(e)), d == {"a": 9, "b": 7, "c": 3, "d": 4})
  1. A. ['b', 'a', 'd', 'c'] ['b', 'a', 'd', 'c'] c True
  2. B. ['b', 'a', 'c', 'd'] ['b', 'a', 'c', 'd'] d True
  3. C. ['b', 'a', 'd', 'c'] ['a', 'd', 'c', 'b'] b True
  4. D. ['b', 'a', 'd', 'c'] ['b', 'a', 'd', 'c'] c False

Correct answer: A. ['b', 'a', 'd', 'c'] ['b', 'a', 'd', 'c'] c True

A dict remembers the order in which keys were FIRST inserted; overwriting a value (d['a'] = 9, update(b=7), {**d, 'b': 0}) never moves a key. Only removing and re-adding does: pop('c') followed by assignment sends 'c' to the end, after the newly added 'd'. So both dicts list b, a, d, c and the last key of e is 'c'. Equality of dicts ignores order, hence True. The option that moves 'b' to the end of e assumes a repeated key in a dict display is re-inserted.

More Python Programming questions

Exams that ask this topic