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\"][\
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