ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
d = {"b": 2, "a": 1, "c": 3}
print(sorted(d.items()))
print(dict(sorted(d.items())))
  1. A. [('a', 1), ('b', 2), ('c', 3)] {'a': 1, 'b': 2, 'c': 3}
  2. B. [('b', 2), ('a', 1), ('c', 3)] {'b': 2, 'a': 1, 'c': 3}
  3. C. [('a', 1), ('b', 2), ('c', 3)] {'b': 2, 'a': 1, 'c': 3}
  4. D. TypeError TypeError

Correct answer: A. [('a', 1), ('b', 2), ('c', 3)] {'a': 1, 'b': 2, 'c': 3}

sorted() on .items() sorts the (key, value) tuples by key first (then value as tiebreak), giving alphabetical key order; wrapping the sorted list back in dict() preserves that insertion order, giving a dict ordered a, b, c.

More Python Programming questions

Exams that ask this topic