
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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]
- Related Articles
- How to get a list of all the keys from a Python dictionary?
- Python – Limit the values to keys in a Dictionary List
- C# program to get the List of keys from a Dictionary
- How to Common keys in list and dictionary using Python
- Python - Clearing list as dictionary value
- How to access nested Python dictionary items via a list of keys?
- Properties of Dictionary Keys in Python
- How to create Python dictionary from list of keys and values?
- How to sort a dictionary in Python by keys?
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- Python Extract specific keys from dictionary?
- Python - Cumulative Mean of Dictionary keys
- Keys associated with Values in Dictionary in Python
- How to add new keys to a dictionary in Python?
- Why must dictionary keys be immutable in Python?
