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:
- python how to create a list of all the values in a dictionary
- python how to get the list of all files in a zip archive
- how to create and initialize a list of lists in python
- python how to find all indexes of an item in a list
- python how to get all keys with maximum value in a dictionary
- how to convert a list to dictionary in python
- convert dictionary keys to a list in python