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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s