get python dictionary from string containing key value pairs

后端 未结 3 2100
我在风中等你
我在风中等你 2020-12-03 00:19

i have a python string in the format:

str = \"name: srek age :24 description: blah blah\"

is there any way to convert it to dictionary th

3条回答
  •  隐瞒了意图╮
    2020-12-03 00:59

    without re:

    r = "name: srek age :24 description: blah blah cat: dog stack:overflow"
    lis=r.split(':')
    dic={}
    try :
     for i,x in enumerate(reversed(lis)):
        i+=1
        slast=lis[-(i+1)]
        slast=slast.split()
        dic[slast[-1]]=x
    
        lis[-(i+1)]=" ".join(slast[:-1])
    except IndexError:pass    
    print(dic)
    
    {'age': '24', 'description': 'blah blah', 'stack': 'overflow', 'name': 'srek', 'cat': 'dog'}
    

提交回复
热议问题