Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialjohn larson
16,594 PointsIn researching how to solve this code challenge, I came across this and I passed but I don't really get it
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
def time_machine(integer, time_unit):
if time_unit == "years":
integer, time_unit = integer * 365, "days"
# I was trying to get variables to work for the value in timedelta,
# but it didn't work till I tried what appears to be unpacking
# Though it doesn't seem to be the same as unpacking a dictionary
# I would love some clarity on this, insights welcome :D
return starter + datetime.timedelta(**{time_unit : integer})
1 Answer
Kenneth Love
Treehouse Guest TeacherThe **
unpacks the dictionary into key=value
pairs. Since all of the units, other than "years", are valid as keywords, this is a solid shortcut to the function.
Here's an example:
time_unit = "minutes"
integer = 5
When you call time_machine(integer, time_unit)
and it gets to that last line (because time_unit
isn't "years"), Python creates a new dictionary with {"minutes": 5}
and then unpacks that into a minutes=5
argument for the datetime.timedelta
call.
john larson
16,594 Pointsjohn larson
16,594 PointsThanks Kenneth. It sounds like your saying that key=value pairs are always considered a dictionary? (this may be an understood concept that I'm just starting to get)
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherUh, no.
If I create a function and use
**kwargs
as one of the parameters:def some_function(name, **kwargs):
Then any
key=value
pairs that come in will be put into (packed) thekwargs
dictionary.If I have a dictionary that I want to use the key/value pairs of as arguments, I can unpack the dict into
key=value
arguments when I call a function:some_function("Kenneth", **{"age": "thirty-something", "job": "teacher"})
That's the same as doing:
some_function("Kenneth", age="thirty-something", job="teacher")
but I can do it without knowing all of the keys/values beforehand.