Assigning keys to a dictionary from a string

前端 未结 3 1805
清歌不尽
清歌不尽 2021-01-22 08:34

I have a string called sentence: \'the sly fox jumped over the brown dog\'

I need to create a dictionary called Positions. The key

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-22 09:24

    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)
    

提交回复
热议问题