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

前端 未结 9 982
走了就别回头了
走了就别回头了 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:47

    I believe you want following.

    >>> a = '#one cat #two dogs #three birds'
    >>> b = { x.strip().split(' ')[0] : x.strip().split(' ')[-1] for x in a.strip().split('#') if len(x) > 0 }
    >>> b
    {'three': 'birds', 'two': 'dogs', 'one': 'cat'}
    

    Or even better

    >>> b = [ y   for x in a.strip().split('#') for y in x.strip().split(' ') if len(x) > 0 ]
    >>> c = { x: y for x,y  in zip(b[0::2],b[1::2]) }
    >>> c
    {'three': 'birds', 'two': 'dogs', 'one': 'cat'}
    >>> 
    

提交回复
热议问题