get python dictionary from string containing key value pairs

后端 未结 3 2099
我在风中等你
我在风中等你 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

    Other variation of Aswini program which display the dictionary in original order

    import os
    import shutil
    mystr = "name: srek age :24 description: blah blah cat: dog stack:overflow"
    mlist = mystr.split(':')
    dict = {}
    list1 = []
    list2 = []
    try:
     for i,x in enumerate(reversed(mlist)):
        i = i + 1
        slast = mlist[-(i+1)]
        cut = slast.split()
        cut2 = cut[-1]
        list1.insert(i,cut2)
        list2.insert(i,x)
        dict.update({cut2:x})
        mlist[-(i+1)] = " ".join(cut[0:-1])
    except:
     pass   
    
    rlist1 = list1[::-1]
    rlist2= list2[::-1]
    
    print zip(rlist1, rlist2)
    

    Output

    [('name', 'srek'), ('age', '24'), ('description', 'blah blah'), ('cat', 'dog'), ('stack', 'overflow')]

提交回复
热议问题