在Clojure中,您可以使用assoc-in
更新映射(字典),如果它不存在,则自动创建密钥路径。
(assoc-in {:a 1 :b 3} [:c :d] 33)
{:a 1, :c {:d 33}, :b 3}
get-in
相同:您可以指定键(或列表索引)的路径,它将返回该路径指定的值,如果它不存在,nil
。
(get-in {:a 1, :c {:d 33}, :b 3} [:c :d])
33
(get-in {:a 1, :c {:d 33}, :b 3} [:c :e])
nil
是否有开箱即用的 Python 等效或类似的快捷方式?(是的,我知道我可以自己写狡猾的字典包装器,但我想避免它)。
或者关于这个?
def assoc_in(dct, path, value):
for x in path:
prev, dct = dct, dct.setdefault(x, {})
prev[x] = value
def get_in(dct, path):
for x in path:
prev, dct = dct, dct[x]
return prev[x]
d = {}
assoc_in(d, ['a', 'b', 'c'], 33)
print d
x = get_in(d, ['a', 'b', 'c'])
print x
这个怎么样?
>>> from collections import defaultdict
>>> def cdict():
... return defaultdict(cdict)
...
>>> d = cdict()
>>> d['a']=1
>>> d['b']=3
>>> d
defaultdict(<function cdict at 0x28d3ed8>, {'a': 1, 'b': 3})
>>> d['c']['d'] = 33
>>> d['c']['d']
33
>>> d
defaultdict(<function cdict at 0x28d3ed8>, {'a': 1, 'c': defaultdict(<function cdict at 0x28d3ed8>, {'e': defaultdict(<function cdict at 0x28d3ed8>, {}), 'd': 33}), 'b': 3})
>>> d['c']['e']
defaultdict(<function cdict at 0x28d3ed8>, {})
>>>
它在未找到的键上返回一个空cdict()
,而不是nil
或None
但除此之外,我认为它的行为相同。
repr
可以做一些工作!