I'm looking for an elegant way to extract some values from a Python dict into local values.
Something equivalent to this, but cleaner for a longer list of values, and for longer key/variable names:
d = { 'foo': 1, 'bar': 2, 'extra': 3 }
foo, bar = d['foo'], d['bar']
I was originally hoping for something like the following:
foo, bar = d.get_tuple('foo', 'bar')
I can easily write a function which isn't bad:
def get_selected_values(d, *args):
return [d[arg] for arg in args]
foo, bar = get_selected_values(d, 'foo', 'bar')
But I keep having the sneaking suspicion that there is some other builtin way.
namedtuple
into multiple variables in a single statement. E.g.foo, bar = get_selected_values(some_func_returns_named_tuple(), 'foo', 'bar')
rather thanmy_named_tuple = some_func_returns_named_tuple(); foo = my_named_tuple.foo; bar = my_named_tuple.bar
– davidA Feb 27 '17 at 1:42