Search code examples
pythondictionary-comprehension

build a dict using dictionay-comprehension when I get keys and values from the same function


Let's assume I have a complex function get_stuff that takes an int and returns a tuple, the 1st element is of type str. The following example has the same behavior but assume the real function is more complex and can't easily be split in two:

def get_stuff(x):
    return str(5*x),float(3*x)

What I want is to build a dict whose (key,value) pairs are the results of get_stuff when called on a specific set of integers. One way to do that would be:

def get_the_dict(set_of_integers):
    result = {}
    for i in set_of_integers:
        k,v = get_stuff(i)
        result[k] = v
    return result

I would rather use dict comprehension for that, but I don't know if it is possible to split the pair inside the comprehension to catch the key and the value separately.

def get_the_dict_with_comprehension(set_of_integers):
    return {get_stuff(i) for i in set_of_integers} #of course this doesn't work

How can I achieve that?


Solution

  • You can do this, not quite a dictionary comprehension:

    dict(get_stuff(i) for i in range(10))