Reputation: 159
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?
Upvotes: 4
Views: 1629
Reputation: 387617
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 }
Upvotes: 7
Reputation: 12015
Just convert the result of map
to dict
directly
>>> list_of_vals = [2, 4, 6]
>>> dict(map(foo, list_of_vals))
{2: 200, 4: 400, 6: 600}
Upvotes: 2