मराठी

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

प्रश्न

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}
कोड लेखन
Advertisements

उत्तर

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
  या प्रश्नात किंवा उत्तरात काही त्रुटी आहे का?
पाठ 4: Working with Lists and Dictionaries - Programming Problems [पृष्ठ ७७]

APPEARS IN

एनसीईआरटी Informatics Practices [English] Class 11
पाठ 4 Working with Lists and Dictionaries
Programming Problems | Q 9. | पृष्ठ ७७
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×