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()))- A. [('a', 5), ('b', 4), ('c', 3)]
- B. [('b', 4), ('c', 3), ('a', 5)]
- C. [('b', 4), ('a', 5), ('c', 3)]
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- What is printed? (prefix sums for range queries) python a = [3, -2, 5, 1, -4, 6] P = [0] for x in a: P.append(P[-1] + x) q = [(0, 2), (1…
- What is printed? (difference array for range increments) python n = 6 diff = [0] (n + 1) for l, r, v in [(0, 2, 5), (1, 4, 3), (3, 5…
- What is printed? (Python sort stability with a key) python recs = [("amit", 82), ("bina", 90), ("chirag", 82), ("dev", 75), ("esha", 90)]…
- What is printed? (finding the k-th node from the end with two pointers) python vals = [11, 22, 33, 44, 55, 66] def kthend(k): lead = trail…
- What is printed? (C: array passed to a function decays to a pointer) c void f(int a[]) { printf("%zu ", sizeof(a) / sizeof(a[0])); } int…
- What is printed? (balanced brackets with a counter only) python def bycounter(s): c = 0 for ch in s: c += 1 if ch == '(' else -1 if c < 0…