5 ms·
def u(**kwargs): return tuple(kwargs.values()) Am I missing something, is this effectively the same? *I realize the tuple can be omitted here
by andy99 1y ago
def u(**kwargs):
return tuple(kwargs.values())
Am I missing something, is this effectively the same?
*I realize the tuple can be omitted here
- sischoel 1y agoOr use itemgetter: >>> from operator import itemgetter >>> dct = {'greeting': 'hello', 'thing': 'world', 'farewell': 'bye'} >>> thing, greeting = itemgetter("thing", "greeting")(dct) >>> thing 'world' >>> greeting 'hello'
- deleted 1y ago[deleted]
- giingyui 1y ago[dead]
- notpushkin 1y agoOhhh, 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.attrgetter https://docs.python.org/3/library/operator.html#operator.att...
- sischoel 1y agoDotted 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.
- masklinn 1y agoTFA looks things up by key, and allows pulling a subset of the dict.
- Grikbdl 1y agoYours relies on ordering, OP's presumably does not.
- Izkata 1y agoYou 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.