How to transform string of space-separated key,value pairs of unique words into a dict

前端 未结 9 897
走了就别回头了
走了就别回头了 2020-11-30 14:22

I\'ve got a string with words that are separated by spaces (all words are unique, no duplicates). I turn this string into list:

s = \"#one cat #two dogs #th         


        
9条回答
  •  有刺的猬
    2020-11-30 14:36

    The problem is whenever you delete a value from the list, that particular list restores its values dynamically. That is, when you perform out.remove(ind) and out.remove(ind+1), the values in these indexes are deleted, but they are replaced with new values which are predecessor of the previous value.

    Therefore to avoid this you have to implement the code as follows :

    out = []
    out = '#one cat #two dogs #three birds'.split()
    
    print "The list is : {0} \n".format(out)
    myDictionary = dict()
    
    for x in out:
    
        if '#' in x:
            ind = out.index(x)  # Get current index
            nextValue = out[ind+1]  # Get next value
            myDictionary[x] = nextValue
    
    out = []  # #emptying the list
    print("The dictionary is : {0} \n".format(myDictionary))
    

    So, after you are done transferring the values from the list to dictionary, we could safely empty the out by using out = []

提交回复
热议问题