←back to thread

101 points _ZeD_ | 7 comments | | HN request time: 0.312s | source | bottom
1. andy99 ◴[] No.44538191[source]

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

*I realize the tuple can be omitted here

replies(4): >>44538290 #>>44538355 #>>44539536 #>>44539641 #
2. Grikbdl ◴[] No.44538290[source]
Yours relies on ordering, OP's presumably does not.
3. Izkata ◴[] No.44538355[source]
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.
4. sischoel ◴[] No.44539536[source]
Or use itemgetter:

  >>> from operator import itemgetter
  >>> dct = {'greeting': 'hello', 'thing': 'world', 'farewell': 'bye'}
  >>> thing, greeting = itemgetter("thing", "greeting")(dct)
  >>> thing
  'world'
  >>> greeting
  'hello'
replies(2): >>44539632 #>>44540387 #
5. ◴[] No.44539632[source]
6. masklinn ◴[] No.44539641[source]
TFA looks things up by key, and allows pulling a subset of the dict.
7. giingyui ◴[] No.44540387[source]
There are so many things like this one in the standard library that it kinda pisses me off when I discover a new one.