Was it helpful?

Question


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

 Live Demo

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

 Live Demo

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]
raja
Published on 09-Sep-2020 12:23:05

Was it helpful?
Not affiliated with Tutorialspoint
scroll top