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}
Odisha ChseTextbookSubjective· 3mImportance★★★★★est
80% · 24/30 Questions
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:
| ch | action | dictionary after |
|---|---|---|
| w | new key, count 1 | {'w': 1} |
| 3 | new key, count 1 | {'w': 1, '3': 1} |
| r | new key, count 1 | ... 'r': 1 |
| e | new key, count 1 | ... 'e': 1 |
| s | new key, count 1 | ... 's': 1 |
| o | new key, count 1 | ... 'o': 1 |
| u | new key, count 1 | ... 'u': 1 |
| r | existing key -> 1 + 1 | ... 'r': 2 |
| c | new key, count 1 | ... 'c': 1 |
| e | existing 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.