Psychedelic Panda
Psychedelic Panda

Reputation: 23

How to return a dictionary and multiple variables from a function in python?

I am trying to set up a function that records to 2 variables and a dictionary, the dictionar works but the two variables return the wrong things

mydict{}
fname = 0
lname = 0

def enterdetails(fname, lname):
    fname = input ("First Name: ");
    fnamedict = fname
    mydict['FirstName'] = fnamedict;

   lname = input ("Last Name: ");
   lnamedict = lname
   mydict['LastName'] = lnamedict;
   print(fname)
   print(lname)

   return mydict
   return (fname, lname)

fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)

However the variables of fname and lname come out as FirstName and LastName respectively. How would I fix this?

Upvotes: 2

Views: 4135

Answers (3)

Maru
Maru

Reputation: 11

The dictionary works because you have it set as a global variable. However, the function is actually returning the "dictionary" first, so your unpacking is all messed up.

Remove the return mydict or use return mydict, (fname, lname), so you will end up with:

mydict, (fname, lname) = enterdetails(fname, lname)

But as I mentioned above, mydict is a global variable, so it is unnecessary to return the value.

Upvotes: 1

Vizjerei
Vizjerei

Reputation: 1030

You can't put a return under a return like

return mydict
return (fname, lname) #this won't return any thing

One of the ways that you could do is:

  ....
  return [mydict, fname, lname]

data = enterdetails(fname, lname)
mydict = data[0]
fname = data[1]
lname = data[2]

Upvotes: 0

Anshul Goyal
Anshul Goyal

Reputation: 76887

You have two return statements, but only the first is returned. Instead, return all three variables together as a tuple:

def enterdetails(fname, lname):
    ...
    return mydict, fname, lname

mydict, fname, lname = enterdetails(fname, lname)
print(fname, lname)
print(mydict)

Upvotes: 4

Related Questions