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())))- A. [('a', 1), ('b', 2), ('c', 3)] {'a': 1, 'b': 2, 'c': 3}
- B. [('b', 2), ('a', 1), ('c', 3)] {'b': 2, 'a': 1, 'c': 3}
- C. [('a', 1), ('b', 2), ('c', 3)] {'b': 2, 'a': 1, 'c': 3}
- 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
- What is printed? python from functools import lrucache calls = [] @lrucache(maxsize=None) def f(n): calls.append(n) return n n f(2); f(3)…
- What is printed? python def deco(f): def wrapper(a, k): wrapper.calls += 1 return f(a, k) wrapper.calls = 0 return wrapper @deco def h()…
- What is printed? python def decoratorwithargs(prefix): def actual(f): def wrapper(a, k): return prefix + str(f(a, k)) return wrapper…
- What is printed? python class A: def init(self): self.x = 1 def enter(self): return self def exit(self, a): self.x = 0 return False with…
- What is printed? python class R: @property def x(self): return 5 r = R() try: r.x = 10 except AttributeError: print("AttributeError")
- What is printed? python try: raise TypeError("t") except (ValueError, TypeError) as e: print("caught", type(e).name)