在一般情况下,我们如何对嵌套dicts进行递归访问?
from collections import defaultdict
D = lambda: defaultdict(D)
d = D()
keys = ['k1', 'k2', 'k3']
value = 'v'
if len(keys) == 3:
k1, k2, k3 = keys
d[k1][k2][k3] = value
else:
???
我走了reduce
,d.__getitem__
和d.__setitem__
的可怕道路,但觉得肯定会有更优雅的方式......
答案 0 :(得分:3)
这很丑陋,但这很有效:
def set_val(d, keys, val):
reduce(lambda x,y: x[y], keys[:-1], d)[keys[-1]] = val
稍微可读的版本:
def set_val(d, keys, val):
last = keys[-1] # Key we want to set val on
search_keys = keys[:-1] # Keys we need to traverse
reduce(lambda x,y: x[y], search_keys, d)[last] = val
用法:
>>> from collections import defaultdict
>>> D = lambda: defaultdict(D)
>>> d = D()
>>> set_val(d, ['k1', 'k2', 'k3'], "hi")
>>> d
defaultdict(<function <lambda> at 0x7fbd365ac7d0>, {'k1': defaultdict(<function <lambda> at 0x7fbd365ac7d0>, {'k2': defaultdict(<function <lambda> at 0x7fbd365ac7d0>, {'k3': 'hi'})})})
>>> d['k1']['k2']['k3']
'hi'
它使用reduce
来达到请求的最内层字典(keys[:-1]
),然后将列表中的最终键设置为所需的值(output_of_reduce[keys[-1]] = val
)。
请注意,在Python 3中,您需要functools import reduce
来使用此功能。
为了清晰起见,这里扩展了代码:
def set_val(d, keys, val):
out = d
for k in keys[:-1]:
out = out[k]
out[keys[-1]] = val
答案 1 :(得分:2)
你可以使用递归。不能说它比循环更优雅或更pythonic,或者使用reduce。
def assign(dct, keylist, value):
if not keylist:
dct = value
else:
dct[keylist[0]] = assign(dct[keylist[0]], keylist[1:], value)
return dct
if __name__ == '__main__':
from collections import defaultdict
D = lambda: defaultdict(D)
d = D()
keys = ['k1', 'k2', 'k3']
value = 'v'
assign(d, keys, value)
print d['k1']['k2']['k3']
[prints] 'v'