Data Structures & AlgorithmsModerateWipro · Accenture pattern

What is printed? (Python dict ordering and update)

What is printed? (Python dict ordering and update)
d = {"b": 1, "a": 2}
d["c"] = 3
d["b"] = 4
del d["a"]
d["a"] = 5
print(list(d.items()))
  1. A. [('a', 5), ('b', 4), ('c', 3)]
  2. B. [('b', 4), ('c', 3), ('a', 5)]
  3. C. [('b', 4), ('a', 5), ('c', 3)]
  4. D. [('c', 3), ('b', 4), ('a', 5)]

Correct answer: B. [('b', 4), ('c', 3), ('a', 5)]

Since Python 3.7 dicts keep insertion order. Updating an existing key ('b') keeps its position; deleting 'a' and inserting it again puts it at the end. Lookups stay O(1) average.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic