我有一个嵌套的Python字典,需要将某个键设置为某个值。例如,
x['key1']['key2']['key3'] = value
如果我事先知道层次结构,则此方法有效。不是这种情况。我正在寻找一种可以在运行时指定以访问所需键值对的寻址方案,例如“ key1 / key2 / key3”。有什么建议吗?
答案 0 :(得分:0)
作为一种方法的开始,您可以将'key1/key2/key3'
之类的字符串解析为可以实现所需功能的函数。例如:
# Assuming for this example that s is just a `/`-delimted string of keys.
def make_getter(s):
keys = s.split("/")
def _(d):
rv = d
for k in keys:
try:
rv = rv.get(k)
except AttributeError:
rv = None
break
return rv
return d
然后
>>> accessor = make_getter("foo/bar/baz")
>>> accessor({'foo': {'bar': {'baz': 3}}})
3
>>> accessor({'foo': 9})
None
答案 1 :(得分:-1)
您可以使用递归方法搜索嵌套的字典表示形式,直到找到'key1',然后返回[key1] [key2] [key3]查找。假设key1在数据结构中没有重复。
In [9]: def lookup(key, nested_dict):
...: for k, v in nested_dict.items():
...: if k == key:
...: return v
...: if isinstance(v, dict):
...: val = lookup(key, v)
...: if val:
...: return val
...: return None
In [10]: a = {'b' :{'c':{'d':1}}, 'f':2}
In [11]: lookup('d', a)
Out[11]: 1
In [12]: lookup('b', a)
Out[12]: {'c': {'d': 1}}
In [13]: lookup('c', a)
Out[13]: {'d': 1}