Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign dictionary values to several variables in a single line (so I don't have to run the same funcion to generate the dictionary for each one)

So I have a function that returns a dictionary. The problem is that I want to assign the values of the dictionary to multiple variables, so I have to run the function several times. Is there a way to do this running the function only one time? Is there any elegant way to do this?

def myFunction():
    a=1
    b=2
    c=3
    d=4
    
    df_out={"a":a, "b":b,"c":c,"d":d}
    
a1=myFunction()["a"]
b1=myFunction()["b"]
c1=myFunction()["c"]
d1=myFunction()["d"]

Thanks in advance!

like image 848
Victorbug Avatar asked Oct 23 '25 16:10

Victorbug


2 Answers

def myFunction():
    a=1
    b=2
    c=3
    d=4

    return {"a":a, "b":b,"c":c,"d":d}

a1, b1, c1, d1 = myFunction().values()
like image 162
bigbounty Avatar answered Oct 26 '25 17:10

bigbounty


Assign the result to a variable, then assign each variable.

d = myFunction()
a1 = d["a"]
b1 = d["b"]
c1 = d["c"]
d1 = d["d"]

I don't think there's a one-liner for this.

like image 23
Barmar Avatar answered Oct 26 '25 18:10

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!