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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With