parse a dot seperated string into dictionary variable

前端 未结 4 358
北荒
北荒 2021-01-25 08:27

I have string values as,

\"a\"
\"a.b\"
\"b.c.d\"

How to convert them into python dictionary variables as,

a
a[\"b\"]
b[\"c\"][\         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 09:19

    s = "a.b.c"
    s = s.replace(".", "][")+"]" # 'a][b][c]'
    i = s.find("]") # find the first "]"
    s = s[:i]+s[i+1:] # remove it 'a[b][c]'
    s = s.replace("]", "\"]").replace("[", "[\"") # add quotations 'a["b"]["c"]'
    # you can now execute it:
    v = eval(s)
    

提交回复
热议问题