In this article we will discuss how to create a list of all keys in a dictionary.

Suppose we have a dictionary of string and integers i.e.

Now how to get all the keys from above dictionary in a list  i.e.

Creating a list of all keys in dictionary using dict.keys()

In python, dictionary class provides a member function i.e.

It returns a view object or iterator to the list of all keys in dictionary.  We can use this object for iteration or creating new list. Let’s use that to get the list of all keys in the above dictionary.

dictkeys content will be,

Creating a filtered list of dictionary keys using List Comprehension

Suppose from above mentioned dictionary, we want a list of keys that start with character ‘t’ only i.e.

let’s do that using for loop i.e.

dictkeys content will be,

But that’s not pythonic. Let’s do that using list comprehension,

dictkeys content will be,

Top 5 online Python courses for beginners in 2019- 2020

Complete example is as follows,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.