Can one write a concise expression that evaluates to an existing dictionary except with some of the elements replaced (modified, substituted)? Example:
a = {'x': 3, 'y': 8}
I'd like to write an expression that evaluates to a dict with the 'x' element's value incremented by one:
{'x': 4, 'y': 8}
I don't want to modify a
(as in a['x'] += 1
); I want to treat a
as immutable. I could do this:
a = {'x': 3, 'y': 8}
a_copy = a.copy()
a_copy['x'] += 1
then reference a_copy
. But is there a more succinct approach that doesn't require an additional variable? (I need to reference the resultant dictionary only once.) Performance isn't a concern.
Dictionary comprehensions can be used to generate a new dictionary, but I want an expression that returns a slight variation of an existing dictionary.