Q.Write a Python program to create a dictionary from a string ‘w3resource’ such that each individual character mates a key and its index value for fist occurrence males the corresponding value in dictionary.
Expected output : {'3': 1, 's': 4, 'r': 2, 'u': 6, 'w': 0, 'c': 8, 'e': 3, 'o': 5}
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 →Loop over the string with enumerate() and add char: index to the dictionary only if the
character isn't already a key — that "only first time" guard is what keeps the first
occurrence's index. (The stem's odd wording — "mates a key", "males the value" — is a typo for
makes: each character becomes a key, its first index the value.)
The idea
'w3resource' has a repeated letter (r at indices 2 and 7, e at 3 and 9). If we wrote
d[ch] = i unconditionally, a later occurrence would overwrite the earlier index. The guard
if ch not in d blocks that overwrite, preserving the first occurrence.
Program
# Dictionary of character -> index of FIRST occurrence
text = 'w3resource'
d = {}
for i, ch in enumerate(text): # enumerate yields (index, character) pairs
if ch not in d: # keep only the FIRST occurrence's index
d[ch] = i
print(d)
Dry run
| i | ch | Already a key? | Action |
|---|---|---|---|
| 0 | w | no | d['w'] = 0 |
| 1 | 3 | no | d['3'] = 1 |
| 2 | r | no | d['r'] = 2 |
| 3 | e | no | d['e'] = 3 |
| 4 | s | no | d['s'] = 4 |
| 5 | o | no | d['o'] = 5 |
| 6 | u | no | d['u'] = 6 |
| 7 | r | yes | skipped — index 2 kept |
| 8 | c | no | d['c'] = 8 |
| 9 | e | yes | skipped — index 3 kept |
Output
{'w': 0, '3': 1, 'r': 2, 'e': 3, 's': 4, 'o': 5, 'u': 6, 'c': 8}
This contains exactly the same 8 key-value pairs as the book's expected output
{'3': 1, 's': 4, 'r': 2, 'u': 6, 'w': 0, 'c': 8, 'e': 3, 'o': 5} — only the printing order …
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.