Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Dictionaries Teacher Stats

Obtaining Unknown Dictionary Elements

How do I get the first key of a dictionary, if I don't know what's in the dictionary?

Here's my code, where I assumed that "Kenneth Love" would be a key.

Even though I used this method, I think it should have worked...?

1 Answer

Nathan Tallack
Nathan Tallack
22,158 Points

Dictionaries are unordered by default (there is a ordered dictionary type but you are not learning that here).

So there is no "first" key as such.

What you can do is get a list of keys via the keys method. If your dictionary is named my_dict you could get a list of keys via my_dict.keys() which returns a list. You could iterate over that list.

Something like this.

my_dict = { "title1": "book1", "title2": "book2", "title3": "book3" }
for key in my_dict.keys():
    print(my_dict[key])

That would result in this output.

book2
book1
book3

Remember, unordered. :)

Thank you!

Chris Freeman
Chris Freeman
Treehouse Moderator 67,986 Points

Additionally, when a dict is used in a iterator context like a for loop, the default action is to iterate over the dict keys. So the following are equivalent:

# using 'key()' method
for key in my_dict.keys():
    print(my_dict[key])

# using default action:
for key in my_dict.:
    print(my_dict[key])

To complete the topic, you can iterate over the values of a dict using my_dict.values(), and you can iterate over a tuples of key / value pairs using my_dict.items().

Nathan Tallack
Nathan Tallack
22,158 Points

Oh wow. I did not know that the default action was to use the keys method. That is awesome.

I really should start reading the header files for some of these types so that I can learn cool things like that. But there is just so much content here on TT that I hardly find time to do any research myself. :P