In Python it is possible to read a dictionary/hash key while at the same time setting the key to a default value if one does not already exist.
For example:
If you only want to modify the value returned by setdefault
, you can express this via Hash#merge!
:
Python:
>>> d = {}
>>> d.setdefault("k", []).append("v")
>>> d
{'k': ['v']}
Ruby:
[28] pry(main)> h = {}
=> {}
[29] pry(main)> h.merge!(k: [:v]) { |_key, old, new| old.concat(new) }
=> {:k=>[:v]}
[30] pry(main)> h
=> {:k=>[:v]}