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 trialVamsi Pavan Mahesh Gunturu
4,541 PointsI don't understand the for loop part
I don't understand the for loop part for key,value in kwargs.items(): setattr(1,2,3)
3 Answers
Kenneth Love
Treehouse Guest Teacherfor key, value in kwargs.items():
This is a pretty common way of getting the key and the key's values from a dictionary in one step instead of two. kwargs
is a dictionary. Calling .items()
on a dict gives you a bunch of tuples with two items in them, the key and the value. Since Python lets us unpack those tuples into variables, we can give two variables to use for each step of the loop. In this case, we're saying to call the key, key
, and the value, value
.
KAZUYA NAKAJIMA
8,851 PointsTeacher Kennith: When I input kwarg as dict, such as {element : 'fire' }, I got Name error.
troll = Monster({element: 'fire'})
# Name error : name 'element' is not defined
below is valid and troll has element attribute 'fire' after below code
troll = Monster(element = 'fire')
I can't understand why first example is incorrect, because kwarg is dict. Is there any good explanation or python documents to read? thank you for your help.
Kenneth Love
Treehouse Guest TeacherDictionary keys have to be valid elements. Since you don't have a variable named element
, the dictionary can't be created. troll = Monster({'element': 'fire'})
would have been accepted (assuming your Monster
class can take a dictionary).
Most of the time we want to unpack our dictionaries when they're provided to a function or class, though. So you'd want troll = Monster(**{'element': 'fire'})
.
And you're correct. **kwargs
is a dictionary, but only on the other side (inside of the function/method). It has to be an unpacked dictionary or a bunch of keywords on the outside of the function/method.
KAZUYA NAKAJIMA
8,851 PointsTeacher Kenneth: thank you for your reply.
below code worked well. you helped me a lot.
troll = Monster(**{'element': 'fire'}).
Vamsi Pavan Mahesh Gunturu
4,541 PointsVamsi Pavan Mahesh Gunturu
4,541 PointsOf course you would not post, But I want to have an opinion from you regarding some thing I want to develop. What would be the best place?
Kenneth Love
Treehouse Guest TeacherKenneth Love
Treehouse Guest TeacherI wouldn't post them in this thread, but, sure, you can talk about non-Treehouse stuff on the forums.