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 trial
Nathan McGinley
4,627 PointsDictionary (.values,.keys,.items) methods
I'm getting a little ahead of myself in the course but I wondered if anyone could tell me why when using the methods above like so:
for key, value in my_dict.items():
print('{}: {}'.format(key.title(), value))
We can gain access to the tuple in the view objects but when I try and do something like this:
dct = {
'name': 'bob',
'job': 'cook',
'feet': 2,
'loves': 'cake'
}
my_keys = []
my_keys = dct.keys()
my_keys[1]
I get the error "TypeError: 'dict_keys' object does not support indexing".
I can fix thix by converting it to an array like so:
...
my_keys.extend(dct.keys())
print(my_keys)
print(my_keys[1])
But where is the conversion in the for loop?
2 Answers
Chris Freeman
Treehouse Moderator 68,468 PointsUsing the keys() method returns a special dict_keys object that cannot be indexed, but can be iterated over.
When iterated over, the keys are ordered according to their hashed values. So they won't be in a natural order, but will be deterministic meaning as long as the set of keys hasn't changed the order of iterated keys will be the same.
One way to get a list of keys is to use list() to iterate over the dict_key object
>>> dict1 = {'keys':0, 'in':1, 'a': 2, 'dict': 3, 'are': 4, 'hash': 5, 'ordered': 6}
>>> key_list = list(dict1.keys())
>>> key_list
['a', 'dict', 'ordered', 'in', 'keys', 'are', 'hash']
>>> key_list[0]
'a'
If the dict keys haven't changed, the list order will also be the same. This is true independent on the values stored in the dict. Changing values does not effect the hashed key order.
>>> dict1['a'] = "new value"
>>> list(dict1.keys())
['a', 'dict', 'ordered', 'in', 'keys', 'are', 'hash']
The for loop doesn't convert the keys to a list. Instead it iterates over the dict_keys object. Behind the scenes it does the following:
# staring with dict_keys object
>>> dict1_keys_obj = dict1.keys()
# the __iter__() method is called to return an iterable
>>> dict1_keys_obj_iter = dict1_keys_obj.__iter__()
# each for-loop iteration, next() is used to get next item
>>> dict1_keys_obj_iter.__next__()
'a'
>>> dict1_keys_obj_iter.__next__()
'dict'
>>> dict1_keys_obj_iter.__next__()
'ordered'
>>> dict1_keys_obj_iter.__next__()
'in'
Steven Parker
243,306 PointsDictionaries have no specific order, so they cannot be indexed. But they can be iterated, which is what the loop is doing.
If indexing it did return a value, there's no way to know which item it would return. Similarly with the values if you were able to do this: dct.values()[2], but you couldn't predict which value you'd get. But you can do this: dct['job'], which in this case will always returrn 'cook'.
Nathan McGinley
4,627 PointsNathan McGinley
4,627 PointsThanks Chris, this gave me a few extra things to go and learn about but it really helped explain the nuances of those specific dictionary methods and for loops.
Sorry to hassle you, but you seem rather knowledgeable on Python and I was wondering if there was a book(s) you would recommend me reading after finishing the Treehouse course.
Chris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsThere was no singular book that I'd pick. I have read through Learning Python, Programing Python, and the Python Cookbook. I've also worked through Two Scoops of Django.
Reading a lot of code to understand what is going on (and fixing my own broken code) is the best teacher. Also other online tutorials and code contest sites like http://checkio.org, http://codingbat.com/python, http://exercism.io/languages/python and others.
Finally, I learn a lot from reading forum posts here and on StackOverflow (500,000+ Python related questions)
That should keep you busy
The learning never stops.