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
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
