按路径(字符串)获取字典键 [英] get dictionary key by path (string)
本文介绍了按路径(字符串)获取字典键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一条可以随时更改的路径:
I have this path that can change from time to time:
'#/path/to/key'
路径的部分未定义,因此此值也很好
The parts of the path aren't defined, so this value is also fine
'#/this/is/a/longer/path'
我将此键分割为'/',所以我得到
I'm splitting this key at '/' so I get
['#', 'path', 'to', 'key']
,我需要输入键在这个路径中,假设我的字典是exp,所以我需要去这里:
and I need to get to the key in this path, let's say my dict is exp, so I need to get to here:
exp['path']['to']['key']
我怎么可能知道如何获取此密钥?
how could I possibly know how to get to this key?
推荐答案
使用递归,路加...
Use the recursion, Luke ...
def deref_multi(data, keys):
return deref_multi(data[keys[0]], keys[1:]) \
if keys else data
last = deref_multi(exp, ['path','to','key'])
这篇关于按路径(字符串)获取字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文