Jan
Jan

Reputation: 5162

Shortcut for unrolling a dictionary

Say, I have a dictionary of data and their variable names, e.g.

dct = {'a': 1, 'b': 2, 'c':3}

and I want to retrieve the values associated with a subset of keys. How can I do this without coding too much, i.e. extracting the variables one-by-one? Is there something like

a, c = dct['a','c']

Upvotes: 1

Views: 2789

Answers (5)

iruvar
iruvar

Reputation: 23364

operator.itemgetter is handy for this

d = {'a':1,'b':2,'c':3}
from operator import itemgetter
a, c = itemgetter('a', 'c')(d)
print a, c
1 3

Upvotes: 1

Sylvain Leroux
Sylvain Leroux

Reputation: 52000

Like functional style ?

>>> d = {'a':1,'b':2,'c':3}

>>> a, c = map(d.get, ('a','c'))
>>> a, c
(1, 3)

Upvotes: 1

abarnert
abarnert

Reputation: 365777

You can use a generator expression for this:

>>> d = {'a':1,'b':2,'c':3}
>>> a, c = (d[key] for key in ['a', 'c'])
>>> a
1
>>> c
3

If you do this often enough that it's worth wrapping up in a function, that's trivial:

>>> def multiget(mapping, *keys):
...     return (d[key] for key in keys)
>>> a, c = multiget(d, 'a', 'c')

However, if you look carefully, you'll see that multiget is just operator.itemgetter uncurried, and it's usually a lot simpler to just use that:

>>> a, c = operator.itemgetter('a', 'c')(d)

Upvotes: 5

jamylak
jamylak

Reputation: 133564

For educational purposes:

>>> d = {'a':1,'b':2,'c':3}
>>> globals().update((k, d[k]) for k in ('a', 'c'))
>>> a
1
>>> c
3

However never actually use something like this

Upvotes: 1

TerryA
TerryA

Reputation: 59984

You almost had it :p

>>> a, c = dct['a'], dct['c']
>>> a
1
>>> c
3

Please don't use dict as a variable name :). It's already a built-in type and function, so you've just overridden it :p.

Upvotes: 1

Related Questions