parse a dot seperated string into dictionary variable

前端 未结 4 400
北荒
北荒 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:01

    The pyjq library does something quite similar to this, except you have to explicitly provide a dictionary to be the root, and you have to prefix your strings with a . to refer to whatever dictionary was your root.

    python:

    import pyjq
    d = { 'a' : { 'b' : { 'c' : 'd' } } }
    for path in ['.a', '.a.b', '.b.c.d', '.x']:
        print(pyjq.first(path, d))
    

    output:

    {'b': {'c': 'd'}}
    {'c': 'd'}
    None
    None
    

提交回复
热议问题