How to copy a dict and modify it in one line of code

Solution 1:

The simplest way in my opinion is something like this:

new_dict = {**old_dict, 'changed_val': value, **other_new_vals_as_dict}

Solution 2:

You could use keyword arguments in the dictionary constructor for your updates

new = dict(old, a=1, b=2, c=3)

# You can also unpack your modifications
new = dict(old, **mods)

This is equivalent to:

new = old.copy()
new.update({"a": 1, "b": 2, "c": 3})

Source

Notes

  • dict.copy() creates a shallow copy.
  • All keys need to be strings since they are passed as keyword arguments.