2-dim Dictionary,键为字符串

skl*_*gel 1 python variables dictionary key

我有一个可能很简单的问题,但我还没有找到解决方案.我试图在字符串varialbe的帮助下访问2-dim字典,但无法正确访问它.在代码的上下文中,我可以将键保存在字符串变量中,这一点非常重要

一个简单的例子:

x = {"one":{"one":1},"two":2}
s1 = "two"
x[s1]                                                                                                                                      
2                                                                                                                                              
s2 = '["one"]["one"]'                                                                                                                                            
x[s2]
Traceback (most recent call last):                                                                                                             
File "<stdin>", line 1, in <module>                                                                                                          
KeyError: '["one"]["one"]'                                                                                                                       
Run Code Online (Sandbox Code Playgroud)

有没有将这个2-Dim键存储到变量中,以便以后访问该字典?

jam*_*lak 5

最好的方法是使用tuple键而不是像这样的字符串.

>>> # from functools import reduce (uncomment in Py3)
>>> x = {"one":{"one":1},"two":2}
>>> def access(d, keys):
        return reduce(dict.get, keys, d)


>>> access(x, ("two", ))
2
>>> access(x, ("one", "one"))
1
Run Code Online (Sandbox Code Playgroud)