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

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,159 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 68,423 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,159 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