English

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

Advertisements
Advertisements

Question

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}
Code Writing
Advertisements

Solution

string = "w3resource"
dictionary = {}
for i in range(len(string)):
    if string[i] not in dictionary:
        dictionary[string[i]] = i
print(dictionary)

Output:

{'w': 0, '3': 1, 'r': 2, 'e': 3, 's': 4, 'o': 5, 'u': 6, 'c': 8}

Explanation:

  • The string is "w3resource".
  • Each character is used as a key.
  • Its first occurrence index is stored as the value.
  • If a character appears again, it is not added again because we check if string[i] not in dictionary.
shaalaa.com
  Is there an error in this question or solution?
Chapter 4: Working with Lists and Dictionaries - Programming Problems [Page 77]

APPEARS IN

NCERT Informatics Practices [English] Class 11
Chapter 4 Working with Lists and Dictionaries
Programming Problems | Q 9. | Page 77
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×