I have a string called sentence: \'the sly fox jumped over the brown dog\'
I need to create a dictionary called Positions.
The key
since the character might be repeated in string, i am storing them as a list
str = "the sly fox jumped over the brown dog"
char_items = list(str)
dictionary = {}
for index,character in enumerate(char_items):
if character not in dictionary.keys():
dictionary[character] = [] # because same character might be repeated in different positions
dictionary[character].append(index)
for character,positions in dictionary.items():
print(character, positions)
You could do something like this:
result = {}
s = 'the sly fox jumped over the brown dog'
for i, c in enumerate(s):
result.setdefault(c, []).append(i)
print(result)
Output
{'m': [14], 'e': [2, 16, 21, 26], 'v': [20], 's': [4], 'n': [32], 'h': [1, 25], 'w': [31], 'l': [5], 'o': [9, 19, 30, 35], 'x': [10], 'p': [15], 'd': [17, 34], 'g': [36], 't': [0, 24], 'u': [13], 'f': [8], 'y': [6], 'b': [28], 'j': [12], ' ': [3, 7, 11, 18, 23, 27, 33], 'r': [22, 29]}
Note that the above solution contemplates the case for repeated characters and it creates a list of the indices.
Thanks, all, for suggestions! As Asif suggested above, the way forward for me was to convert the string into a list.