-2

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.

Ineedhelp
  • 41
  • 1
  • 1
  • 6
  • 2
    You are `return`ing within the `for` loop so the function exits after storing the first value in the dictionary. – T Burgis Oct 18 '18 at 15:43
  • SO is not a place where you come to learn how to use 'for' loop. Find a good programming resource and learn and practice a bit of coding. – Ajeet Ganga Oct 18 '18 at 18:01

1 Answers1

2

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.

Leszek Kicior
  • 183
  • 2
  • 8