Is there a python function to return a new dict with a new key added, like assoc in clojure?
Sure, you can simply use dict()
, for example:
old = {"a": 1}
new_one = dict(old, new_key=value)
#or
new_one = dict(old, {...})
Since Python 3.9, you can also use Dictionary Merge and Update Operators, although some may argue that is less explicit.
The code snippet would become:
old = {"a": 1}
# 1. Merge operator
new_one = old | {"new_key": value}
## `old_one` is {"a": 1}
## `new_one` is {"a": 1, "new_key": value}
# 2. Update operator
old |= {"new_key": value}
## `old_one` becomes {"a": 1, "new_key": value}