Skip to content
Programming Problems · Q9

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}

CBSENCERTSubjective· 3mImportance★★★★★est
97% · 29/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 →

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

ichAlready a key?Action
0wnod['w'] = 0
13nod['3'] = 1
2rnod['r'] = 2
3enod['e'] = 3
4snod['s'] = 4
5onod['o'] = 5
6unod['u'] = 6
7ryesskipped — index 2 kept
8cnod['c'] = 8
9eyesskipped — 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.