Python · Question 21 · Medium

What will be the output of the following Python code?

d = {}
for ch in "banana":
    d[ch] = d.get(ch, 0) + 1
print(d)
  1. {'b': 1, 'a': 1, 'n': 1}
  2. {'a': 3, 'b': 1, 'n': 2}
  3. {'b': 1, 'a': 3, 'n': 2}
  4. {'b': 0, 'a': 2, 'n': 1}
Answer and explanation

Answer: C. {'b': 1, 'a': 3, 'n': 2}

Explanation: get returns the current count or 0, then 1 is added, so each letter is counted. Dictionaries keep insertion order (b first, then a, then n), giving {'b': 1, 'a': 3, 'n': 2}.

Previous: What will be the output of the following Python code? · Next: What will be the output of the following Python code?

Practise python

Try a fresh set of python questions with an explanation after every answer, free and without signing up: Python practice. Or sit a full placement mock test.

More python questions

More technical & programming practice

Data Structures · Algorithms · Object-Oriented Programming · DBMS · SQL · Operating Systems · Computer Networks · Software Engineering

LogicWiz Exams home · All practice topics · Placement mock tests · Daily 10 challenge