parse a dot seperated string into dictionary variable

前端 未结 4 355
北荒
北荒 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 08:55

    eval is fairly dangerous here, since this is untrusted input. You could use regex to grab the dict name and key names and look them up using vars and dict.get.

    import re
    
    a = {'b': {'c': True}}
    
    in_ = 'a.b.c'
    match = re.match(
        r"""(?P      # begin named group 'dict'
              [^.]+        #   one or more non-period characters
            )              # end named group 'dict'
            \.             # a literal dot
            (?P      # begin named group 'keys'
              .*           #   the rest of the string!
            )              # end named group 'keys'""",
        in_,
        flags=re.X)
    
    d = vars()[match.group('dict')]
    for key in match.group('keys'):
        d = d.get(key, None)
        if d is None:
            # handle the case where the dict doesn't have that (sub)key!
            print("Uh oh!")
            break
    result = d
    
    # result == True
    

    Or even more simply: split on dots.

    in_ = 'a.b.c'
    input_split = in_.split('.')
    d_name, keys = input_split[0], input_split[1:]
    
    d = vars()[d_name]
    for key in keys:
        d = d.get(key, None)
        if d is None:
            # same as above
    result = d
    

提交回复
热议问题