Hy and creating new dictionaries from old ones

I was recently asked on irc if Hy has something equivalent to following snippet of Python code:

>>> x = {"a": 123}
>>> dict(foo=1, **x)
{'a': 123, 'foo': 1}

The closes I could come up with is following:

=> (setv x {"a" 123})
=> (apply dict [(, (, "foo" 1))] x)
{"foo" 1, "a" 123}

The end result is the same, although it isn’t exactly the same snippet of code, as it’s closer to one below:

>>> dict((("foo", 1),), **x)
{'a': 123, 'foo': 1}

Lots of dicts with various syntaxes here, but what does all that mean and where would that be useful?

The net effect in all cases is that:

  • Original dictionary x isn’t modified
  • A new dictionary is created with content of x and new key-value pair of “foo”: 1.

This is useful when you want to pretend to be working with immutable data-structures and keep the dictionary passed in to a function unchanged, while returning something that is equal to the original + some more.

apply by the way is used to apply optional list of arguments and optional dictionary of key-value pairs to a function. Thus, it’s akin to foo(*args, **kwargs) call in Python.