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

Python Dictionary keys() method

Last Updated : 21 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
# 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'])

Python Dictionary keys() method – FAQs

What Does the keys() Method Do in Python?

The keys() method in Python is used with dictionaries to return a view of all the keys in the dictionary. This view object reflects the changes made to the dictionary, meaning if the dictionary is updated, the view shows the new keys.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['a', 'b', 'c'])

How to Reference Keys in Dictionary in Python?

Keys in a dictionary can be referenced using the square bracket notation similar to indexing arrays but using the key name instead of numerical indexes.

Example:

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict['a'] # Access the value associated with the key 'a'
print(value) # Output: 1

What Does object.keys() Do?

In the context of Python, object.keys() might seem misleading as Python objects do not have a direct keys() method. However, in JavaScript, Object.keys() is a method used to return an array of a given object’s own enumerable property names, iterated in the same order that a normal loop would. If you’re dealing with Python, ensure you’re using this method with dictionaries only.

Can a Dictionary Have Duplicate Keys?

No, a dictionary in Python cannot have duplicate keys. Each key must be unique within a dictionary. If you attempt to assign a value to an already existing key, the previous value associated with that key will be overwritten with the new value.

Example:

my_dict = {'a': 1, 'b': 2}
my_dict['a'] = 3 # This will overwrite the value of key 'a' from 1 to 3
print(my_dict) # Output: {'a': 3, 'b': 2}

Which Key is Used to Define Methods in Python?

The term “key” isn’t typically used to describe defining methods in Python. Instead, methods are defined using the def keyword followed by the method name and parameters.

Example:

class MyClass:
def my_method(self):
print("Hello, World!")

# Creating an instance of MyClass
obj = MyClass()
obj.my_method() # Output: Hello, World!

The def keyword is crucial for defining both standalone functions and methods within classes in Python. There is no specific “key” used in this context



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 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 | Check if given multiple keys exist in a dictionary
A dictionary in Python consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value. Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "practice"} Output : Yes Input : dict[] = {"geeksforgeeks" : 1, "practice" : 2, "contribute" :3} keys[] = {"geeksforgeeks", "
3 min read
Python | Test if dictionary contains unique keys and values
Sometimes, we just wish to work with unique elements and any type of repetition is not desired, for these cases, we need to have techniques to solve these problems. One such problem can be to test for unique keys and values. For keys, they are by default unique, hence no external testing is required, but as for values, we need to have ways to do it
6 min read
Python - Keys associated with value list in dictionary
Sometimes, while working with Python dictionaries, we can have a problem finding the key of a particular value in the value list. This problem is quite common and can have applications in many domains. Let us discuss certain ways in which we can Get Keys associated with Values in the Dictionary in Python. Example Input: {'gfg': [4, 5], 'best': [10,
4 min read
Python - Find dictionary keys present in a Strings List
Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the extraction of dictionary keys from strings list feeded. This problem can have application in many domains including data. Lets discuss certain ways in which this task can be performed. Method #1: Using list comprehension This is brute force way in
7 min read
Python - Unique value keys in a dictionary with lists as values
Sometimes, while working with Python dictionaries, we can have problem in which we need to extract keys with values that are unique (there should be at least one item not present in other lists), i.e doesn't occur in any other key's value lists. This can have applications in data preprocessing. Lets discuss certain ways in which this task can be pe
4 min read
Python - Keys associated with Values in Dictionary
Sometimes, while working with Python dictionaries, we can have problem in which we need to reform the dictionary, in the form in which all the values point to the keys that they belong to. This kind of problem can occur in many domains including web development and data domains. Lets discuss certain way in which this task can be performed. Input :
5 min read
How to Add Duplicate Keys in Dictionary Python
In Python, dictionaries are used to store key-value pairs. However, dictionaries do not support duplicate keys. In this article, we will see how to store multiple values for a single key using two simple approaches. Understanding Dictionary Key ConstraintsIn Python, dictionary keys must be unique. This means that if you try to add a key that alread
3 min read
Python | Add new keys to a dictionary
Before learning how to add items to a dictionary, let's understand in brief what a dictionary is. A Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other data types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is provided in the dictionary t
8 min read
Python | Pretty Print a dictionary with dictionary value
This article provides a quick way to pretty How to Print Dictionary in Python that has a dictionary as values. This is required many times nowadays with the advent of NoSQL databases. Let's code a way to perform this particular task in Python. Example Input:{'gfg': {'remark': 'good', 'rate': 5}, 'cs': {'rate': 3}} Output: gfg: remark: good rate: 5
7 min read
Handling missing keys in Python dictionaries
In Python, dictionaries are containers that map one key to its value with access time complexity to be O(1). But in many applications, the user doesn't know all the keys present in the dictionaries. In such instances, if the user tries to access a missing key, an error is popped indicating missing keys. Handling Missing Keys in Python DictionariesI
4 min read
Python | Pandas dataframe.keys()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.keys() function returns the 'info axis' for the pandas object. If the pandas object is series then it returns index. If
1 min read
Python | Pandas Series.keys()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.keys() function is an alias for index. It returns the index labels of the given
2 min read
Python IMDbPY – Info set to keys of Movie object
In this article we will see how we can convert info set to keys, we can know info sets of movie by get_movie_infoset, but even after getting the info set we are unable to use like dictionary. In order to use info set as dictionary keys we have to use infoset2keys method. Syntax : movie.infoset2keys Here movie is the imdb Movie object Action perform
2 min read
Python IMDbPY – Info set to keys of Person object
In this article we will see how we can convert info set to keys, we can know info sets of movie by get_person_infoset, but even after getting the info set we are unable to use like dictionary. In order to use info set as dictionary keys we have to use infoset2keys method. Syntax : person.infoset2keys Here movie is the imdb Person object Action perf
3 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Python - Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let's discuss the certain ways in which this task can be
7 min read
Special Keys in Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Special Keys is an exclusive feature of Selenium in python, that allows pressing keys through keyboard such as ctrl+f, or shift+c+v, etc. class selenium.webdriver.common.keys.Keys handles all Keys in Selenium Python. It contains huge number of key methods one can use in Sel
1 min read
Convert ImmutableMultiDict with duplicate keys to list of lists in Python
In this article, we are going to see how to convert ImmutableMultiDict with duplicate keys to a list of lists using Python. Using Werkzeug Python Werkzeug is a WSGI utility library. WSGI is a protocol or convention that assures that your web application can communicate with the webserver and, more crucially, that web apps can collaborate effectivel
3 min read
Python - Find the Common Keys from two Dictionaries
In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see different methods to do the task at hand and why they wo
4 min read
Python - Counter.items(), Counter.keys() and Counter.values()
Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python’s general-purpose built-ins like dictionaries, lists and tuples. Counter is a sub-class that is used to count hashable objects. It imp
3 min read
Python Dictionary fromkeys() Method
Python dictionary fromkeys() function returns the dictionary with key mapped and specific value. It creates a new dictionary from the given sequence with the specific value. Python Dictionary fromkeys() Method Syntax: Syntax : fromkeys(seq, val) Parameters : seq : The sequence to be transformed into a dictionary.val : Initial values that need to be
3 min read
Python Dictionary setdefault() Method
Python Dictionary setdefault() returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to the dictionary. Python Dictionary setdefault() Method Syntax: Syntax: dict.setdefault(key, default_value)Parameters: It takes two parameters: key - Key to be searched in the dictionary. default_value (optional) -
2 min read
Python Dictionary popitem() method
Python dictionary popitem() method removes the last inserted key-value pair from the dictionary and returns it as a tuple. Python Dictionary popitem() Method Syntax: Syntax : dict.popitem() Parameters : None Returns : A tuple containing the arbitrary key-value pair from dictionary. That pair is removed from dictionary. Note: popitem() method return
2 min read
Use get() method to create a dictionary in Python from a list of elements
Prerequisites: Get() method for dictionaries in Python The naive approach for creating a dictionary from a list of items we can use the for loop. See the below example for better understanding. Example: li =['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a'] di ={} for ele in li: # Increase the value of key # if exists if ele in di: di[ele]= di[ele]+1 else: #
2 min read
Combine similar characters in Python using Dictionary Get() Method
Let us see how to combine similar characters in a list. Example : Input : ['g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's'] Output : ['gg', 'eeee', 'kk', 'ss', 'f', 'o', 'r'] We will be using the get() method of the dictionary class. dictionary.get() The get() method returns the value of the item with the specified key. Syntax : dic
3 min read
Python Dictionary pop() Method
Python dictionary pop() method removes and returns the specified element from the dictionary. Example: C/C++ Code # inializing dictionary student student = {"rahul":7, "Aditya":1, "Shubham":4} # priting original dictionary print(student) # using dictionary pop suspended = student.pop("rahul") # checking key o
4 min read
Python Dictionary items() method
As of Python 3.7, dictionaries are ordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, a Dictionary holds a key: value pair.In Python Dictionary, items() are the list with all dictionary keys with values. Syntax: dictionary.items()Parameters: This metho
2 min read
Python Dictionary get() Method
Python Dictionary get() Method returns the value for the given key if present in the dictionary. If not, then it will return None (if get() is used with only one argument). Python Dictionary get() Method Syntax:Syntax : Dict.get(key, Value) Parameters: key: The key name of the item you want to return the value fromValue: (Optional) Value to be retu
4 min read