The Wayback Machine - https://web.archive.org/web/20240607224549/https://www.geeksforgeeks.org/python-dictionary-keys-method/
Open In App

Python Dictionary keys() method

Last Updated : 16 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python.

Syntax: dict.keys()

Parameters: There are no parameters.

Returns: A view object is returned that displays all the keys. This view object changes according to the changes in the dictionary.

Method 1: Accessing the key using the keys() method

A simple example to show how the keys() function works in the dictionary.

Python3




# Dictionary with three keys
Dictionary1 = {'A': 'Geeks', 'B': 'For', 'C': 'Geeks'}
 
# Printing keys of dictionary
print(Dictionary1.keys())


Output: 

dict_keys(['A', 'B', 'C'])

Method 2: Python access dictionary by key

Demonstrating the practical application of keys() using the Python loop.

Python3




# initializing dictionary
test_dict = {"geeks": 7, "for": 1, "geeks": 2}
 
# accessing 2nd element using naive method
# using loop
j = 0
for i in test_dict:
    if (j == 1):
        print('2nd key using loop : ' + i)
    j = j + 1


Output: 

2nd key using loop : for
TypeError: 'dict_keys' object does not support indexing 

Time Complexity: O(n)
Auxiliary Space: O(n)

Note: The second approach would not work because dict_keys in Python 3 do not support indexing. 

Method 3: Accessing key using keys() indexing

Here, we first extracted all the keys and then we implicitly converted them into the Python list to access the element from it.

Python3




# initializing dictionary
test_dict = {"geeks": 7, "for": 1, "geeks": 2}
 
# accessing 2nd element using keys()
print('2nd key using keys() : ', list(test_dict.keys())[1])


Output: 

2nd key using keys() :  for

Method 4: Python Dictionary update() function

To show how to update the dictionary keys using the update() function. Here, when the dictionary is updated, keys are also automatically updated to show the changes.

Python3




# Dictionary with two keys
Dictionary1 = {'A': 'Geeks', 'B': 'For'}
 
# Printing keys of dictionary
print("Keys before Dictionary Updation:")
keys = Dictionary1.keys()
print(keys)
 
# adding an element to the dictionary
Dictionary1.update({'C': 'Geeks'})
 
print('\nAfter dictionary is updated:')
print(keys)


Output: 

Keys before Dictionary Updation:
dict_keys(['B', 'A'])

After dictionary is updated:
dict_keys(['B', 'A', 'C'])


Previous Article
Next Article

Similar Reads

Different ways of sorting Dictionary by Keys and Reverse sorting by keys
Prerequisite: Dictionaries in Python A dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. We can access the values of the dictionary using keys. In this article, we will discuss 10 different ways of sorting the Python dictionary by keys and a
8 min read
Python - Append Dictionary Keys and Values ( In order ) in dictionary
Given a dictionary, perform append of keys followed by values in list. Input : test_dict = {"Gfg" : 1, "is" : 2, "Best" : 3} Output : ['Gfg', 'is', 'Best', 1, 2, 3] Explanation : All the keys before all the values in list. Input : test_dict = {"Gfg" : 1, "Best" : 3} Output : ['Gfg', 'Best', 1, 3] Explanation : All the keys before all the values in
5 min read
Python Program to create a sub-dictionary containing all keys from dictionary list
Given the dictionary list, our task is to create a new dictionary list that contains all the keys, if not, then assign None to the key and persist of each dictionary. Example: Input : test_list = [{'gfg' : 3, 'is' : 7}, {'gfg' : 3, 'is' : 1, 'best' : 5}, {'gfg' : 8}]Output : [{'is': 7, 'best': None, 'gfg': 3}, {'is': 1, 'best': 5, 'gfg': 3}, {'is':
8 min read
Python - Extract selective keys' values Including Nested Keys
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract selective keys' values. This problem has been solved earlier, but sometimes, we can have multiple nestings and certain keys may be present in inner records. This problem caters all the nestings for extraction of keys' values. Let's discuss certain w
7 min read
Python | Split dictionary keys and values into separate lists
Given a dictionary, the task is to split a dictionary in python into keys and values into different lists. Let's discuss the different ways we can do this. Example Input: {'a': 'akshat', 'b': 'bhuvan', 'c': 'chandan'} Output: keys: ['a', 'b', 'c'] values: ['akshat', 'bhuvan', 'chandan']Method 1: Split dictionary keys and values using inbuilt functi
5 min read
Python - Filter immutable rows representing Dictionary Keys from Matrix
Given Matrix, extract all the rows which has elements which have all elements which can be represented as dictionary key, i.e immutable. Input : test_list = [[4, 5, [2, 3, 2]], ["gfg", 1, (4, 4)], [{5:4}, 3, "good"], [True, "best"]] Output : [['gfg', 1, (4, 4)], [True, 'best']] Explanation : All elements in tuples are immutable. Input : test_list =
7 min read
Python dictionary with keys having multiple inputs
Prerequisite: Python-Dictionary. How to create a dictionary where a key is formed using inputs? Let us consider an example where have an equation for three input variables, x, y, and z. We want to store values of equation for different input triplets. Example 1: C/C++ Code # Python code to demonstrate a dictionary # with multiple inputs in a key. i
4 min read
Python - Cumulative Mean of Dictionary keys
Given the dictionary list, our task is to write a Python Program to extract the mean of all keys. Input : test_list = [{'gfg' : 34, 'is' : 8, 'best' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9, 'and' : 5, 'best' : 12}, {'geeks' : 8, 'find' : 3, 'gfg' : 3, 'best' : 8}] Output : {'gfg': 12.666666666666666, 'is': 8, 'best': 10, 'for': 10, 'geeks': 8.5,
6 min read
Python program to Swap Keys and Values in Dictionary
Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value so that they can be retrieved efficiently. Let’s discuss various ways of swapping the keys and values in Python Dictionary. Method#1 (Does not work when there are multiple same values): One naive solution maybe something like just swa
4 min read
Python | Remove spaces from dictionary keys
In Python, dictionary is a collection which is unordered, changeable and indexed. Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. Let's see how to remove spaces from dictionary keys in Python. Method #1: Using translate() function here we visit each key one by one and remove space wi
5 min read