6. Keys, values, items

A dictionary has three view methods:

They take no arguments. Each returns a view object, not a list: it reflects the dictionary and shows its own type name when printed:

A view is iterable, so you can pass it to list() when you need a real list:

The order follows the dictionary's insertion order.

Coming from JavaScript? d.keys(), d.values() and d.items() are like Object.keys(), Object.values() and Object.entries(), but they are lazy views, not arrays. Wrap them in list() when you need a list.

#01

Print the keys

Create person = {"name": "Ada", "age": 36}. Print the result of calling keys() on the dictionary.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Print the values

With the same person = {"name": "Ada", "age": 36}, print the result of calling values() on the dictionary.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Print the items

With the same person = {"name": "Ada", "age": 36}, print the result of calling items(). Each item is a (key, value) tuple.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Turn the keys into a list

A view is not a list. Pass person.keys() to list() to build a real list, then print it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.