Skip to content
Programming Problems · Q4

Q.Write a Python program to create a dictionary from a string.
Note: Track the count of the letters from the string.
Sample string : 'w3resource'
Expected output : {'3': 1, 's': 1, 'r': 2, 'u': 1, 'w': 1, 'c': 1, 'e': 2, 'o': 1}

Sikkim CbseNCERTSubjective· 3mImportance★★★★★est
80% · 24/30 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

One pass over the string with d[ch] = d.get(ch, 0) + 1 builds the letter-frequency dictionary; the counts match the book exactly, and only the key order differs (modern Python preserves insertion order).

The idea. Frequency counting is the signature use of a dictionary: the thing being counted is the key, the count is the value. The neat trick is dict.get(ch, 0) — it returns the existing count if ch is already a key and 0 if it is not, so one line handles both the "first time seen" and "seen again" cases.

Program:

st = 'w3resource'
d = {}
for ch in st:
    d[ch] = d.get(ch, 0) + 1    # get() returns 0 if ch is not yet a key
print(d)

Verified output (Python 3.7+):

{'w': 1, '3': 1, 'r': 2, 'e': 2, 's': 1, 'o': 1, 'u': 1, 'c': 1}

Step-by-step trace of the interesting characters:

chactiondictionary after
wnew key, count 1{'w': 1}
3new key, count 1{'w': 1, '3': 1}
rnew key, count 1... 'r': 1
enew key, count 1... 'e': 1
snew key, count 1... 's': 1
onew key, count 1... 'o': 1
unew key, count 1... 'u': 1
rexisting key -> 1 + 1... 'r': 2
cnew key, count 1... 'c': 1
eexisting key -> 1 + 1... 'e': 2

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.