Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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

*I realize the tuple can be omitted here



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.


Or use itemgetter:

  >>> from operator import itemgetter
  >>> dct = {'greeting': 'hello', 'thing': 'world', 'farewell': 'bye'}
  >>> thing, greeting = itemgetter("thing", "greeting")(dct)
  >>> thing
  'world'
  >>> greeting
  'hello'


Ohhh, nice. Also, attrgetter (which also supports dotted notation to get nested attrs! Sadly, no dotted notation for itemgetter.)

https://docs.python.org/3/library/operator.html#operator.att...


Dotted notation would not work because the keys in a dict can also contain dots. I am not terrible familiar with them but there is something called `lenses` that comes from functional programming that should allow you to access nested structures. And I am pretty sure there must be at least one python library that implements that.


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


TFA looks things up by key, and allows pulling a subset of the dict.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: