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

A stupid but easy question: printing key names in a dictionary

Is there a way of only returning the key names? as in

my_dict = {'a' : 1, 'b': 2}

and I want to get back 'a' and 'b'? printing "my_dict" will return the whole dictionary and this (code below) will return every value associated to the key:

for key in my_dict:
    print(my_dict[key])

But if I just want to print all the key names? I'm sure it's very simple!

2 Answers

In Python 3 my_dict.keys() will give you a dictionary view object that you can iterate over.

To get a plain old list you can use list(my_dict.keys()).

list(my_dict) also works, but the former is more explicit so you might prefer it.

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher
for key in my_dict:
    print(key)

Looping through a dict only gets the keys.