
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Dictionary Keys as a List in Python
For many programs getting the keys from a dictionary is important input to be used by some other program which rely on this dictionary. In this article we are going to see how to capture the keys as a list.
Using dict.keys
This is a very direct method of accessing the keys. This method is available as a in-built method.
Example
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'} print("The given dictionary is :\n ",Adict) print(list(Adict.keys()))
Output
Running the above code gives us the following result −
The given dictionary is : {1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'} [1, 2, 3, 4]
Using *
The * can be applied to any iterable. So the keys of a dictionary can be directly accessed using * which is also called unpacking.
Example
Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'} print("The given dictionary is :\n ",Adict) print([*Adict])
Output
Running the above code gives us the following result −
The given dictionary is : {1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'} [1, 2, 3, 4]
Using itemgetter
The itemgetter(i) constructs a callable that takes an iterable object like dictionary,list, tuple etc. as input, and fetches the i-th element out of it. So we can use this method to get the keys of a dictionary using the map function as follows.
Example
from operator import itemgetter Adict = {1:'Sun',2:'Mon',3:'Tue',4:'Wed'} print("The given dictionary is :\n ",Adict) print(list(map(itemgetter(0), Adict.items())))
Output
Running the above code gives us the following result −
The given dictionary is : {1: 'Sun', 2: 'Mon', 3: 'Tue', 4: 'Wed'} [1, 2, 3, 4]