Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack function return tuple into key value pair

Suppose I have a function that returns a tuple:

def foo(x):
  return (x, x*100)

I have a list of values that I'd like to apply the function on and then turn the results into a dictionary:

list_of_vals = [2, 4, 6]
result = {...magic comprehension...}
print(result)
# {2: 200, 4: 400, 6: 600}

I've come up with two ways to do this:

{ k: v for k, v in map(foo, list_of_vals)}
{ k: v for k, v in (foo(val) for val in list_of_vals} # equivalently

or:

def helper_bar(vals):
  for val in vals:
    yield(foo(val))

{k: v for k, v in helper_bar(vals)}

However, none of these is very readable. Furthermore, if the list_of_vals is humongous I don't want to create extra copies. Is there any better (efficient?) way to do this assuming I have very long list of values and foo is an expensive function?

like image 545
Rudimentary Joe Avatar asked Oct 20 '25 02:10

Rudimentary Joe


1 Answers

You can also use the dict initializator that takes an iterable of key-value tuples. So this would be perfect for your function that already returns a tuple:

>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}

In general though, having a function that returns a key-value tuple with the identical key seems somewhat rare. Most commonly, you would just have a function that returns the value. In those cases you would use a dictionary comprehension like this:

{ x: foo(x) for x in list_of_vals }
like image 72
poke Avatar answered Oct 22 '25 04:10

poke