Convert Dictionary keys to a List in Python

In this article, we will discuss different ways to convert all keys of a python dictionary to a list.

Table of Contents

Convert all keys of dictionary to list using list()

In Python, a dictionary object is also an iterable object, which can be used to iterate over all keys of dictionary. So, we can pass this iterable object to the list() function, it will return a list containing all keys of the dictionary. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# Convert all keys of dictionary to list
list_of_keys = list(word_freq)

print(list_of_keys)

Output:

['Hello', 'at', 'test', 'this', 'why', 'Hi', 'How']

We created a list of all keys of the dictionary.

Convert all keys of dictionary to list using List Comprehension

In Python, dictionary class provides a function items(), which returns an iterable sequence (dict_items) of all key-value pairs of dictionary. We can use the list comprehension to iterate over all items of the dictionary using the sequence returned by items() and create a list of keys only. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# List of all keys of a dictionary
list_of_keys = [key 
                for key, value in word_freq.items()]

print(list_of_keys)

Output:

['Hello', 'at', 'test', 'this', 'why', 'Hi', 'How']

We created a list of all keys of the dictionary.

In both the above examples, we converted all keys of a dictionary to a list. But what if we want to convert only specific keys from a dictionary to a list? Let’s see how to do that,

Convert specific keys of dictionary to list

Suppose we want to convert only selected keys from a dictionary to a list. Like, select only those keys of dictionary whose value is greater than 50 and create a list of those keys only. To achieve that, we can apply an if condition while iterating over pairs of dictionary and select only those keys where condition returns the True. For example,

# Dictionary of string and int
word_freq = {
    "Hello": 56,
    "at": 23,
    "test": 43,
    "this": 78,
    "why": 89,
    "Hi": 51,
    "How": 79
}

# Convert dictionary keys to list where value is greater than 50
selected_keys =[key 
                for key, value in word_freq.items()
                if value > 50]

Output:

['Hello', 'this', 'why', 'Hi', 'How']

We converted only those keys to a list where value was greater than 50.

Summary:

We learned about different ways to convert all or selected keys of a dictionary to a list.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top