Assigning keys to a dictionary from a string

前端 未结 3 1816
清歌不尽
清歌不尽 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)
    
    0 讨论(0)
  • 2021-01-22 09:32

    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.

    0 讨论(0)
  • 2021-01-22 09:38

    Thanks, all, for suggestions! As Asif suggested above, the way forward for me was to convert the string into a list.

    0 讨论(0)
提交回复
热议问题