Return dictionary from function

Question:

I’ve been searching stackoverflow for a few hours now without finding a solution to my problem. I have a function where I want the output to be a dictionary, but I can only get it to print the first key + value. The “yield” statement won’t work for some reason, so I’m wondering if there is another way to do it.

This is my code:

def myfunc(somedict):
    x = list(somedict.values())      
    for i in x:
        data = dict_from_otherfunc(i)
        mylist = [float(max(data.values()))]
        mydict = dict(zip([i], mylist))
        return mydict

This returns a dictionary that looks like this:

{'abc': 1}

When I put print instead of return I get the desired output. How can i make this code return a dictionary with all values instead of only one?

Edit:
Tried returning outside of for-loop, this returns only the last value of my dictionary.

Asked By: Ineedhelp

||

Answers:

EDIT: If I understand correctly, the problem lies in the for loop itself. You set the value of mydict on every iteration, so of course it only returns one of them.

Now, I’m not fully certain if I understand what you’re trying to do, but if I do, I’d recommend trying something like this:

def myfunc(somedict):
    x = list(somedict.values())
    mylist = [float(max(dict_from_otherfunc(i).values()) for i in x] # You can split this into two lines to make it more readable, I suppose
    mydict = dict(zip(x, mylist)
    return mydict

This would also benefit from renaming your variables a bit and such, but I’m assuming this is just an example.

Answered By: Leszek Kicior