将点分隔的字符串解析为字典变量 [英] parse a dot seperated string into dictionary variable

查看:102
本文介绍了将点分隔的字符串解析为字典变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串值,

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

如何将它们转换为python字典变量,

How to convert them into python dictionary variables as,

a
a["b"]
b["c"]["d"]

字符串的第一部分(点前)将成为字典名称,其余子字符串将成为字典键

The first part of the string (before dot) will become the dictionary name and the rest of the substrings will become the dictionary keys

推荐答案

eval在这里非常危险,因为这是不受信任的输入.您可以使用regex来获取字典名称和键名,然后使用varsdict.get查找它们.

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<dict>      # begin named group 'dict'
          [^.]+        #   one or more non-period characters
        )              # end named group 'dict'
        \.             # a literal dot
        (?P<keys>      # 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

这篇关于将点分隔的字符串解析为字典变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆