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

Viewed 62

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?

3 Answers

You can do this, not quite a dictionary comprehension:

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

If you really want to use a dict comprehension, you can do the following:

{k: v for k, v in [get_stuff(i) for i in set_of_integers]}

Instead of a comprehension you can also map the set of integers to the dict constructor with the key-value pairs returned by get_stuff:

dict(map(get_stuff, set_of_integers))
Related