小编Ric*_*nix的帖子

有效地访问任意深度的词典

假设我有一个像这样的多级字典

mydict = {
    'first': {
        'second': {
            'third': {
                'fourth': 'the end'
             }
         }
     }
}
Run Code Online (Sandbox Code Playgroud)

我想像这样访问它

test = get_entry(mydict, 'first.second.third.fourth')
Run Code Online (Sandbox Code Playgroud)

到目前为止我所拥有的是什么

def get_entry(dict, keyspec):
    keys = keyspec.split('.')

    result = dict[keys[0]]
    for key in keys[1:]:
       result = dict[key]

    return result
Run Code Online (Sandbox Code Playgroud)

有更有效的方法吗?根据%timeit,函数的运行时间是1.26us,而访问字典的标准方式是这样的

foo = mydict['first']['second']['third']['fourth']
Run Code Online (Sandbox Code Playgroud)

需要541ns.如果可能的话,我正在寻找将其修剪到800ns范围的方法.

谢谢

python recursion dictionary python-2.7

29
推荐指数
4
解决办法
821
查看次数

标签 统计

dictionary ×1

python ×1

python-2.7 ×1

recursion ×1