Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elegant way to unpack limited dict values into local variables in Python

Tags:

python

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.

like image 452
DonGar Avatar asked Jul 19 '13 20:07

DonGar


People also ask

Can we unpack dictionary in Python?

Unpacking Dictionaries With the ** Operator In the context of unpacking in Python, the ** operator is called the dictionary unpacking operator. The use of this operator was extended by PEP 448. Now, we can use it in function calls, in comprehensions and generator expressions, and in displays.

How do you get all the keys values from a dict?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.


1 Answers

You can do something like

foo, bar = map(d.get, ('foo', 'bar'))

or

foo, bar = itemgetter('foo', 'bar')(d)

This may save some typing, but essentially is the same as what you are doing (which is a good thing).

like image 95
Lev Levitsky Avatar answered Sep 28 '22 12:09

Lev Levitsky