I currently have:
tmp = myfunc()
mydict[mykey] = tmp
return tmp
..which seems a little too long. In javascript, I could just do:
return (mydict[mykey] = myfunc())
Is the above Python code the accepted way to do it, or is there something else?
edit: I'm aware of the possibility of doing:
mydict[mykey] = myfunc()
return mydict[mykey]
..but I wouldn't want to do a key lookup twice. Unless
tmp = mydict[mykey] = myfunc()
return tmp
You can do this if you want less lines of code:
mydict[mykey] = myfunc()
return mydict[mykey]
Assignment isn't an expression in Python, though, so you can't do the javascript version.
EDIT: If you know the key is not in the dictionary, you can do this:
return mydict.setdefault(mykey, myfunc())
setdefault
is a lookup function that sets the key to the 2nd value if the key is not in the dictionary.
You could also write a helper function:
def set_and_return(d, k, v):
d[k] = v
return v
Then, everywhere else, you can do:
return set_and_return(mydict, mykey, myfunc())
Opinions vary but here is my $.02.
@gnibbler
has a nice "fewer lines of code" solution but I wouldn't suggest it and reading a lot of python source I rarely see that syntax (more at the start of a function than anywhere else) I appreciate how it happens in javascript but for the accepted way to do it: I vote for your original format, easiest to read and understand and no slower or less efficient than any other solution.
tmp = myfunc()
mydict[mykey] = tmp
return tmp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.