Reputation: 10058
I have a function which returns a set:
I want to create a dict comprehension and use the set to populate the dictionary keys and values. Need assistant getting the value from function and use it to populate the key and value.
Expected result:
{ 52: [1, 2, 3, 4], 94: [3, 4, 5, 4]}
I have the following code to simplify example: (You can ignore the enumerate)
from random import randint
a1 = [1,2,3]
b1 = [3,4,5]
l = [a1, b1]
def add_value(a):
return randint(0,100), a + [4]
d = {x: add_value(y) for x, y in enumerate(l, start=1)}
print d
Now d prints:
{1: (52, [1, 2, 3, 4]), 2: (94, [3, 4, 5, 4])}
Upvotes: 0
Views: 1014
Reputation: 9267
You can do it like this way
d = {add_value(y)[0]:add_value(y)[1] for y in [a1,b1]}
or
d = dict(add_value(y) for y in [a1,b1])
Upvotes: 0
Reputation: 41
d = {x:y for x,y in [add_value(li) for li in l]}
should work. In this case, you first create a list of tuples returned by the function add_value, then for each item of this list, you unpack the tuple, and add a key:value to the dictionary.
There must be a better way, but your question is harder than it seems at the first view.
Upvotes: 1
Reputation: 78554
I don't see why you're using enumerate
, since you're not working with indices here.
The following would create the dictionary you want using the tuples returned by your function:
d = dict(add_value(x) for x in l)
Upvotes: 2