Skip to content(if available)orjump to list(if available)

Dict Unpacking in Python

Dict Unpacking in Python

11 comments

·July 8, 2025

zdimension

Did not know that such things could be accomplished by registering a new file coding format. Reminds me of https://pypi.org/project/goto-statement/

zahlman

This one is arguably even more of a hack; it's working at the source code level rather than the AST level.

The "coding" here is a bytes-to-text encoding. The Python lexer expects to see character data; you get to insert arbitrary code to convert the bytes to characters (or just use existing schemes the implement standards like UTF-8).

null

[deleted]

zelphirkalt

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.

peter422

I love the union syntax in 3.9+:

  new_dict = old_dict | update_keys_and_values_dict

parpfish

Don’t forget the in place variant!

  the_dict |= update_keys_and_values_dict

sco1

The author also has an accompanying video: https://youtu.be/eqiM0xRmFJg

andy99

  def u(**kwargs):
    return tuple(kwargs.values())
Am I missing something, is this effectively the same?

*I realize the tuple can be omitted here

Izkata

You have to pull them out by key name, and not just get everything. Here's a working version, though with a totally different syntax (to avoid having to list the keys twice, once as keys and once as resulting variable names):

  >>> def u(locals, dct, keys):
  ...     for k in keys:
  ...         locals[k] = dct[k]
  ... 
  >>> dct = {'greeting': 'hello', 'thing': 'world', 'farewell': 'bye'}
  >>> u(locals(), dct, ['greeting', 'thing'])
  >>> greeting
  'hello'
  >>> thing
  'world'
  >>> farewell
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
  NameError: name 'farewell' is not defined

Modifying locals() is generally frowned upon, as there's no guarantee it'll work. But it does for this example.

Grikbdl

Yours relies on ordering, OP's presumably does not.

nine_k

In short, it runs a text preprocessor as the source text decoder (like you would decode from Latin-1 or Shift-JIS to Unicode).