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,

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.