Clojure equivalent of tie-in and get-in in Python

In Clojure you can update the map (dict) with assoc-inand automatically create a key path if it does not exist.

(assoc-in {:a 1 :b 3} [:c :d] 33)
{:a 1, :c {:d 33}, :b 3}

The same for get-in: you can specify the path to the keys (or list indexes), and it will return the value specified in the path nil, if it does not exist.

(get-in {:a 1, :c {:d 33}, :b 3} [:c :d])
33
(get-in {:a 1, :c {:d 33}, :b 3} [:c :e])
nil

Is there a Python equivalent or comparable shortcut out of the box? (yes, I know that I can write deceptive dictations, but I would like to avoid this).

+3
source share
1 answer

How about this?

>>> 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>, {})
>>> 

It returns a blank cdict()key not found, not nilor None, but otherwise I think it behaves the same.

repr can work with little work!

+2
source

All Articles