Victorbug
Victorbug

Reputation: 137

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!

Upvotes: 4

Views: 1863

Answers (3)

bigbounty
bigbounty

Reputation: 17368

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()

Upvotes: 6

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can use operator.itemgetter:

from operator import itemgetter

i = itemgetter('a', 'b', 'c', 'd')
a1, b1, c1, d1 = i(myFunction())

print(a1, b1, c1, d1)

Upvotes: 1

Barmar
Barmar

Reputation: 780869

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.

Upvotes: 1

Related Questions