← Back to context

Comment by zelphirkalt

1 day ago

I found dictionary unpacking to be quite useful, when you don't want to mutate things. Code like:

    new_dict = {**old_dict, **update_keys_and_values_dict}

Or even complexer:

    new_dict = {
        **old_dict,
        **{
            key: val
            for key, val in update_keys_and_values_dict
            if key not in some_other_dict
        }
    }

It is quite flexible.

I love the union syntax in 3.9+:

  new_dict = old_dict | update_keys_and_values_dict

  • Don’t forget the in place variant!

      the_dict |= update_keys_and_values_dict

    • No no, do forget about it: like += for lists, |= mutates “the dict”, which often makes for awkward bugs.

      And like += over list.extend, |= over dict.update is very little gain, and restricts legal locations (augmented assignments are statements, method calls are expressions even if they return "nothing")

      6 replies →