Python dictionary keys as list – Python : How to Create a List of all the Keys in the Dictionary ?

Python dictionary keys as list: Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}

Output:

['This', 'is', 'BTechGeeks']

Create a List of all keys of a Dictionary

There are several ways to create a list of all keys of a dictionary some of them are:

Method #1:Using keys() +list() function

The dictionary class in Python has a member function called dict.keys ()

It returns a view object or an iterator that iterates through the list of all keys in the dictionary. This object can be used for iteration or to create a new list.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using keys() +list() function
keyslist = list(dictionary.keys())
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Method #2 :Using unpacking (*args)

Unpacking with * works with any iterable object, and because dictionaries return their keys when iterated through, it is simple to create a list by using it within a list literal.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using args(*) function
keyslist = [*dictionary]
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Method #3 :Using List Comprehension

We can convert to list using list comprehension in a single line.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using list comprehension
keyslist = [key for key in dictionary]
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Related Programs: